I created Next Js project. I deployed it to my CPanel. And I created server.js file on directory.
I called next module as require in server.js. But When I access to my website I catch an error.
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'next';
This error message.
My server.js code
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const port = !dev ? process.env.PORT : 3000;
// Create the Express-Next App
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
handle(req, res, parsedUrl);
console.log("pathname", pathname);
}).listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
My package json
{
"name": "projectName",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
"dependencies": {
"express": "^4.17.1",
"next": "10.0.6",
"react": "17.0.1",
"react-dom": "17.0.1"
}
}
What should i do?
Thank you.
Best regards
Add this in your package.json dependency section : "#next/env": "^12.0.7"
I've already had problems publishing a next application other than on vercel. To fix the error I had to create a docker in order to publish the application. In case someone doesn't answer with a more viable solution, I recommend looking into using a docker.
Related
Trying to make my first Vue application, simple game with MEVN stack. Working perfect interacting with backend on development environment, however when hosting it doesn't fetch the data from the server.
Anyone able to point out what I have incorrect with the below?
More info below:
File structure:
/root
|- config.js
|- server.js
|- package.json + package-lock.json
|- client/
|- vue.config.json
|- ... (rest of dist, src, node_modules, public etc.)
|- models/
|- Elf.js + HighScore.js
|- routes/
|- api/
|- elf.js + highScore.js
config.js
module.exports = {
hostUrl: process.env.HOST_URL,
mongoURI: process.env.MONGO_URI,
PORT: process.env.PORT || 3000,
};
server.js
const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
const { PORT, mongoURI } = require("./config.js");
// routes
const Player = require("./routes/api/player");
const Elf = require("./routes/api/elf");
const HighScore = require("./routes/api/highScore");
// cors is a middleware that allows us to make requests from our frontend to our backend
const cors = require("cors");
// morgan is a middleware that logs all requests to the console
const morgan = require("morgan");
// body-parser is a middleware that allows us to access the body of a request
const bodyParser = require("body-parser");
const path = require("path");
app.use(cors());
// use tiny to log only the request method and the status code
app.use(morgan("tiny"));
app.use(bodyParser.json());
// chek if we are in production
if (process.env.NODE_ENV === "production") {
// check if we are in production mode
app.use(express.static("client/dist"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "dist", "index.html"));
});
}
// test if server is running and connected to mongoDB
app.get("/", (req, res) => {
res.send("Hello World!");
});
// app.get("/", (req, res) => {
// res.send("Hello World!");
// });
// use routes
app.use("/api/", Player);
app.use("/api/", Elf);
app.use("/api/", HighScore);
mongoose
.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected..."))
.then(() => {
// log uri to console
console.log(`MongoDB connected to ${mongoURI}`);
})
.catch((err) => console.log(err));
app.listen(PORT, () => {
console.log(`Example app listening at ${PORT}`);
});
package.json
{
"name": "week1",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"server": "nodemon server.js --ignore 'client/'",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"start": "node server.js",
"build": "npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"bootstrap": "^5.2.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^6.7.5",
"morgan": "^1.10.0",
"portal-vue": "^2.1.7"
},
"devDependencies": {
"concurrently": "^7.6.0",
"nodemon": "^2.0.20"
}
}
Running within my dev environment at root dir using 'npm run dev', the app works flawlessly send/ receive data from mongoDB during this time. This starts up http://localhost:8080/. Also tried install of 'npm install -g serve' and running 'serve -s dist', this starts up serving at localhost:36797 and working flawlessly too.
I have tried to setup on Vercel & Render, both giving me the same issue where I'm not getting much feedback and the data isn't being fetched. Anyone else has this issue before?
So I followed a tutorial on how to deploy NextJs app to a subdomain on a Cpanel hosting by adding a server.js file and modifying the Package.json file with the following:
// server.js
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost'
const port = process.env.port || 3000
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
if (pathname === '/a') {
app.render(req, res, '/a', query)
} else if (pathname === '/b') {
app.render(req, res, '/b', query)
} else {
handle(req, res, parsedUrl)
}
}).listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://${hostname}:${port}`)
})
})
//Package.json file
...
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "NODE_ENV=production node server.js",
"lint": "next lint",
"json-server": "json-server --watch db.json --port 3004"
}
...
I run npm build and uploaded the files to a folder that points to a subdomain. However, when I create my application in Node.js in Cpanel, the "Run NPM Install" button is greyed out and the information I keep getting is that the package.json cannot be found in the folder meanwhile it is actually there.
Any help on what could be wrong or a link to a better tutorial?
Your application root name should be the same with the application url.
Also ensure you uploaded all your file inside your application root name.
The components needed are the .next/ directory and files next.config.js, package.json and server.js, package-lock.json
Click Stop app button and refresh page.
I'm running Nuxt in Universal Mode with Koa as API / Controller in the backend based on the Koa template. I'm deploying to Heroku. API works fine locally, but returns 404 in production. I think that the app is running as SPA when deployed as everything else works well.
Here's my server/index.js
const Koa = require('koa')
const consola = require('consola')
const Router = require('koa-router');
const { Nuxt, Builder } = require('nuxt')
const api = require('./api');
console.log('server works'); // ------> This line gets ignored by the Heroku console
const app = new Koa()
const router = new Router();
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'
router.use('/api', api.routes(), api.allowedMethods());
app.use(router.routes());
async function start () {
// Instantiate nuxt.js
const nuxt = new Nuxt(config)
const {
host = process.env.HOST || '127.0.0.1',
port = process.env.PORT || 3000
} = nuxt.options.server
// Build in development
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
app.use((ctx) => {
ctx.status = 200
ctx.respond = false // Bypass Koa's built-in response handling
ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
nuxt.render(ctx.req, ctx.res)
})
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`, // ------> Neither this line appears in Heroku console
badge: true
})
}
start()
Procfile
web: nuxt start
Scripts from package.json
"scripts": {
"dev": "cross-env HOST=192.168.1.65 NODE_ENV=development nodemon server/index.js --watch server ",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate",
"test": "ava",
"test:unit": "cross-env TEST=unit ava --config unit.config.js",
"test:e2e": "cross-env TEST=e2e ava --config e2e.config.js",
"heroku-postbuild": "nuxt build"
}
I think I'm getting nu(x)ts after reading all these deployment docs and not seeing the obvious.
Thanks.
I didn't live any problem, attaching my package.json, server/index.js file and Heroku environment settings. You can check herokuapp from here
package.json
{
"name": "testkoa",
"version": "1.0.0",
"description": "My first-class Nuxt.js project",
"author": "Ahmet Zeybek",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate"
},
"dependencies": {
"#nuxtjs/axios": "^5.3.6",
"#nuxtjs/dotenv": "^1.4.0",
"#nuxtjs/pwa": "^3.0.0-0",
"cross-env": "^5.2.0",
"koa": "^2.6.2",
"koa-router": "^7.4.0",
"nuxt": "^2.0.0"
},
"devDependencies": {
"nodemon": "^1.18.9"
}
}
server/index.js
const Koa = require("koa");
const Router = require("koa-router");
const consola = require("consola");
const { Nuxt, Builder } = require("nuxt");
const app = new Koa();
// Import and Set Nuxt.js options
const config = require("../nuxt.config.js");
config.dev = app.env !== "production";
async function start() {
app.use(async function handleError(ctx, next) {
try {
await next();
} catch (err) {
ctx.status = err.statusCode || err.status || 500;
ctx.body = err;
}
});
const router = new Router({ prefix: "/api" });
router.get("/:name", async ctx => {
ctx.response.body = `Hello ${ctx.params.name}`;
});
// Instantiate nuxt.js
const nuxt = new Nuxt(config);
const {
host = process.env.HOST || "127.0.0.1",
port = process.env.PORT || 3000
} = nuxt.options.server;
// Build in development
if (config.dev) {
const builder = new Builder(nuxt);
await builder.build();
} else {
await nuxt.ready();
}
app.use(router.routes());
app.use(router.allowedMethods());
app.use(ctx => {
ctx.status = 200;
ctx.respond = false; // Bypass Koa's built-in response handling
ctx.req.ctx = ctx; // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
nuxt.render(ctx.req, ctx.res);
});
app.listen(port, host);
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
});
}
start();
Heroku Config Vars
HOST=0.0.0.0
NODE_ENV=production
NPM_CONFIG_PRODUCTION=false
You don't need Procfile to use your Nuxt app on Heroku with this
configuration, remove it from your project folder
I am running my Angular Project on npm start and expect it to listen simultaneously to port 3000 (that is suppose to listen automatically to anything that is in the api folder).
Anyway, it looks like it is trying to listen to the port, but it keeps catching an error for who knows what reason
Doing a node BLL.js directly to see if there is a JSON output works like a charm, but having the REST api work does not seem to work weirdly.
package.json
{
"name": "project-vas",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxyConfig.json",
"build": "ng build --env=prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
proxyConfig.json
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true
}
}
api/DBConnection.js
exports.config = function()
{
return config = {
user: 'username',
password: 'password',
server: 'localhost',
database: 'databaseName'
};
}
api/BLL.js
const express = require('express');
const path = require('path');
const sql = require('mssql');
const app = express();
const connection = require('./DBConnection');
let config = connection.config();
const port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/dist/ProjectName/'));
app.get('/*', (require, res) => res.sendFile(path.join(__dirname)));
app.get('api/usertypes', function (req, res) {
sql.connect(config, function (err) {
if (err) { console.log(err); }
else {
var request = new sql.Request();
request.query('sp_GETUSERTYPES', function (err, recordset) {
if (err) {
console.log(err);
}
res.send(recordset);
});
}
});
});
environment.ts
export const environment = {
production: false,
api:"http://localhost:3000",
};
Just the expected Stored Procedure output in the shape of a JSON array.
But 'Error occured while trying to proxy to: localhost:4200/api/usertypes' keeps getting returned whenever I try to test it on Postman.
I'm taking an online course on writing block-chain from scratch.
The course utilizes javascript and node.js.
I am very new to these technologies but followed the course so far to the T.
i'm pasting the relevant code - the app file (index):
const express = require('express');
const bodyParser = require('body-parser');
const Blockchain = require('../blockchain');
const P2pServer = require('./p2p-server');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
const bc = new Blockchain();
const p2pServer = new P2pServer(bc);
app.use(bodyParser.json());
app.get('/blocks', (req, res) => {
res.json(bc.chain);
});
app.post('/mine', (req, res) => {
const block = bc.addBlock(req.body.data);
console.log(`New blovk added: ${block.toString()}`);
res.redirect('/blocks');
});
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();
and the code from p2p-server.js:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
//HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
class P2pServer {
constructor(blockchain) {
this.blockchain = blockchain;
this.sockets = [];
}
listen() {
const server = new Websocket.Server({ port: P2P_PORT });
server.on('connection', socket =>this.connectSocket(socket));
this.connectToPeers();
console.log(`listening to peer-to-peer connections on: ${P2P_PORT}`);
}
connectToPeers() {
peers.forEach(peer => {
const socket = new Websocket(peer);
socket.on('open', () => this.connectSocket(socket));
});
}
connectSocket(socket){
this.sockets.push(socket);
console.log('socket connected');
}
}
module.exports = P2pServer;
when I try to run the following in the command line:
HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
I get the following:
'HTTP_PORT' is not recognized as an internal or external command, operable program or batch file.
for some reason the process.env isn't picking up the input and passing it on to the app. What is wrong here?
Thanks!
EDIT: I was asked to add the package.json:
{
"name": "sf-chain",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --watchAll",
"dev-test": "nodemon dev-test",
"start": "node ./app",
"dev": "nodemon ./app"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^23.1.0",
"nodemon": "^1.17.5"
},
"dependencies": {
"body-parser": "^1.18.3",
"crypto-js": "^3.1.9-1",
"express": "^4.16.3",
"ws": "^5.2.0"
}
}
You are using:
$ HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
It is showing an error, because the window powershell will not recognize this command..
Instead you should use:
set HTTP_PORT=3002 && set P2P_PORT=5002 && set PEERS=ws://localhost:5001 && npm run dev
I believe were doing the same course. I'm sure you've probably figured this out but I tried the same step in Git Bash instead of Powershell and it worked.