How do I correctly create and launch express with npm start? When I do "npm start" I get the following error. Failed at the webserver#1.0.0 start script. I see the following in the error log that hints to the app.js but what is it about the app.js that is incorrect? Thank you.
20 error code ELIFECYCLE
21 error errno 126
22 error webserver#1.0.0 start: `./src/app.js`
22 error Exit status 126
23 error Failed at the webserver#1.0.0 start script.
I have the following package.json file.
{
"name": "webserver",
"preferGlobal": true,
"version": "1.0.0",
"author": "Milton Centeno <centem#gmail.com>",
"description": "a simple express web server",
"license": "MIT",
"main" : "./src/app.js",
"engines": {
"node": ">=0.10"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"express": ">=4.15.3"
}
}
Here is the output of the tree command that shows where my app.js file is relative to package.json.
.
├── node_modules
├── package-lock.json
├── package.json
└── src
└── app.js
And this is what I have for my app.js
// Load the Express package as a module
const express = require("express");
// Access the exported service
const app = express();
// Return a string for requests to the root URL ("/")
app.get("/", (request, response) => {
response.send("Hello from Express!");
});
// Start listening to incoming requests
// If process.env.PORT is not defined, port number 3000 is used
const listener = app.listen(process.env.PORT || 3000, () => {
console.log(`Your app is listening on port ${listener.address().port}`);
});
You need to define a start script: "start": "node src/app.js",.
From the NPM docs:
This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.
Related
I am building a headless CMS with Strapi. I am testing the webhooks section and want to show the received data from the webhook on my React front-end.
I created a new folder webhooks on my local machine and ran npm init -y.
It created a package.json file with this content in it:
{
"name": "webhooks",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
I added a index.js file to the root folder with this content and installed express and body-parser:
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
const PORT = 3001
app.use(bodyParser.json())
app.post("/webhook", (req, res) => {
console.log(req.body)
res.status(200).end()
})
app.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`))
After that I added this line in my package.json:
"start": "node index.js"
So it will start up with npm start instead of node index.js.
I added this URL to my strapi webhooks: http://localhost:3001/webhook and tested the trigger from the Strapi admin. It works fine.
After this I ran npx create-react-app client to create my react front-end app.
My next question is now how can I receive the contents from the webhook in my react front-end app?
I'm trying to run from Docker a simple "hello world" in NodeJS, following a video tutorial. This is my first attempt in nodejs and in Docker so I'm sure I miss something obvious but passing through the video compared to the code I wrote many times, I still can't find the error.
Locally it works fine, but in Docker is unable to run. In Docker Desktop the container becomes green and immediately gray again.
I've tried to change the path many times, thinking that the problem is there but without any clue. I really haven't the experience to investigate further, please help me to solve the issue.
My Dockerfile
FROM node:16
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD ["npm", "run", "dev"]
package.json
{
"dependencies": {
"express": "^4.18.1",
"node": "^18.5.0"
},
"name": "contratti",
"version": "1.0.0",
"description": "prova",
"main": "App.js",
"scripts": {
"start": "node App.js",
"dev": "nodemon -L App.js"
},
"author": "jegor",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.19"
}
}
App.js
const express = require("express");
const app = express();
app.get("/", (req,res) => {
res.send("<h2> Ciao ciao ..</h2>");
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server running at ${port}`));
ZSH
docker run -v $(pwd):/usr/src/app -p 3000:3000 -d --name contratti contratti
Error returned
> contratti#1.0.0 dev
> nodemon -L App.js
/usr/src/app/node_modules/.bin/node: 1: /usr/src/app/node_modules/.bin/node: �����: Input/output error
/usr/src/app/node_modules/.bin/node: 3: /usr/src/app/node_modules/.bin/node: Syntax error: Unterminated quoted string
I am trying to run a server using es6 modules but crashes every time I do it and works whenever I use it with es5error message
I have babel installed and have "preset": ["env"] in my .babelrc file but whenever I run it, I have a "syntax error: Invalid or unexpected token". And this is not on one particular project, this is the third project where am experiencing this
import http from 'http';
import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
// setting up express application
const app = express();
const hostName = '127.0.0.1';
const port = 3000;
const server = http.createServer(app);
// logs request to the console
app.use(logger('dev'))
// Parse incoming data requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
// making a request to the server
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to the default API route',
}));
server.listen(port, hostName, () => {
console.log(`Server running at http://${hostName}:${port}/`);
});
it supposed to bring out "Welcome to the default API route" to the console but instead, it is an error message. And if the repo is needed, i will gladly supply it
ES6 is not yet supported in the Node runtime by default. You can integrate it like this:
npm i esm && npm i -D nodemon
In your package.json, add this to scripts:
"start": "nodemon -r esm index.js"
(make sure the index.js part of the script matches the name of your server entry point file)
Run npm start
Solution to running nodemon with support for ES6 module import/export syntax.
first, install the esm package:
npm i esm
second, ensure package.json contains the line
"type": "module"
example package.json:
line 6
{
"name": "stack-overflow-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"esm": "^3.2.25",
"express": "^4.18.1"
}
}
To run nodemon:
nodemon esm path-to-your/index.js
the file extension is necessary
I try to get a production build in next.js to run it on my server but I can't build next.js production build when I try
npm run build
Does anyone know how to get a prod build in next.js working correctly I did everything in the next.js documentation but always get this error below. If I do a dev build it works just fine but trying prod build results in errors.
I did also next build many times and reinstalled all node_modules packages still having this error.
it always shows me in terminal
Error: Could not find a valid build in the '/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/.next' directory! Try building your app with 'next build' before starting the server.
at Server.readBuildId (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:753:15)
at new Server (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:80:25)
at module.exports (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next.js:6:10)
at Object.<anonymous> (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/next.config.js:6:13)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at loadConfig (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/config.js:47:28)
at _callee2$ (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/build/index.js:52:42)
at tryCatch (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:288:22)
at Generator.prototype.(anonymous function) [as next] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:114:21)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! hello-next#1.0.0 build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hello-next#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/kk/.npm/_logs/2018-12-10T19_58_00_588Z-debug.log
server.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
next.config.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("/projects/:page", (req, res) => {
const page = req.params.page;
let file = "";
switch (page) {
case "example1":
file = "/projects/example1";
break;
case "example2":
file = "/projects/example2";
break;
}
return app.render(req, res, file, { page });
});
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
package.json
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
If anyone has an idea would be so nice! I plan to run this next.js site using node on my AWS server. But to do this I need to get production build of react.js currently I can run just a development build.
Hope someone has an idea.
Thanks in advance!
next build followed by next start should be the right commands to prepare the build for production and run it.
Here's an example for package.json. if you want to export application to run as a static content, something like hosting it in s3 as a static website, you need to run next export
...
"scripts": {
"build": "next build",
"start": "next start",
"export": "next export"
}
...
Make sure you have the above scripts in your package.json then run the following in order
$ npm run build
$ npm run start
If you want to start application with specific port, you can specify -p port as argument for npm run command
npm run start -- -p 3232
If you want to incorporate this into a CI/CD pipeline, you need to have Dockerfile, here's a simple example
FROM node:alpine
#copy source
COPY . /app
# Install deps
RUN cd /app && npm install
# Build
RUN npm run build
ENTRYPOINT [ "npm", "run", "start" ]
Still need more explanation or help, don't hesitate to leave a comment and I will be more than happy to assist.
Seems your server.js config is not correct. Please try moving all you have from your next.config.js to server.js make sure the next.config.js file is empty then create a new npm run script:
"prod_start": "NODE_ENV=production node server.js"
Your package.json should then look like this:
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"prod_start": "NODE_ENV=production node server.js",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
make sure to run: npm run build && npm run prod_start
Then you should have a production build of react running using next.js
Let me know if you got question.
You must launch next build at your root folder and not inside .next/
There are 3 ways todo it:-
way 1: use next build instead of npm run build
way 2: npm run build npm install -g serve serve -s build
more info: https://create-react-app.dev/docs/deployment/
way 3: after npm run build, Remove / from JS,CSS links from /static/index.html file. eg. replace these 2 lines
<script defer="defer" src="/static/js/main.aa87bc08.js"></script>
<link href="/static/css/main.073c9b0a.css" rel="stylesheet"/>
with these 2 lines
<script defer="defer" src="static/js/main.aa87bc08.js"></script>
<link href="static/css/main.073c9b0a.css" rel="stylesheet" />
now it even work on file:///D:/codes/ProjectName/build/index.html
tell me in the comments if none of the 3 ways work, I'll find, try & tell way 4, 5, etc.
I have a node/socket.io chat app hosted on openshift, and while it starts correctly if i ssh into the server and do "node main.js" (where main.js is the server script that starts the chat), I can't start the app on the server by web interface, where it would go on automatically; If i just start the app by ssh, it would stop working as soon as i exit the terminal.
I get this error when starting the app by the web interface:
Starting Node.js application...
Application is already stopped.
Warning! Could not start Node.js application!
Failed to execute: 'control restart' for /var/lib/openshift/57003fbe7628e1491d00011e/nodejs
In case it's relevant, my package.json file is
{
"name": "rainychat",
"version": "1.0.0",
"description": "rainychat, my chat app",
"main": "main.js",
"dependencies": {
"express": "^4.13.4",
"socket.io": "^1.4.5",
"validator": "^5.1.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "JG",
"license": "ISC"
}
And here you can see the files of the app by ftp:
I can't decode what that error means...
My main.js code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/chat.html'); // /home/redadmin/public_html/rainychat.com
console.log('enviado');
});
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');
http.listen(app.get('port'), app.get('ip'), function () {
console.log('Listening on port ' + app.get('port'));
});
//... More code
If you're creating a new Node project, start with npm init to create the package.json file. You can add the --auto option to give it safe defaults.
Remember, the JSON file must be valid JSON, so test it with jsonlint or a tool like an online validator.
Any dependencies your project has should be spelled out in the package file. This is done automatically with things like npm install express --save.