Here's my code for an express server:
const express=require('express');
express();
const app=express();
app.get('/',(req,res)=>{
res.send('Welcome to API xyz!');
});
app.listen(3000,()=>{
console.log('Listening on port 3000...');
});
Running the server from a git bash terminal, in the app's directory, using:
nodemon index.js
initially gives the message:
[nodemon] starting `node index.js`
Listening on port 3000...
Whenever I save a change to the output of res.send() as follows:
res.send('Welcome to API abc!');
and save the index.js file, I get this message:
[nodemon] restarting due to changes...
but I do not get the console.log() text, and when I reload localhost:3000 in Chrome, I still get the output:
Welcome to API xyz!
How can I get the server to update in response to saved changes without having to stop nodemon and restart it (which is the whole point of running nodemon in the first place)?
EDIT: I noticed that when nodemon restarts, I get:
restarting due to changes...
but I don't get
starting `node index.js`
after that. I only get
starting `node index.js`
when I first run nodemon.
EDIT 2: thinking that maybe this is related to the same issue that other nodemon users have experienced, as noted here in its Github issues log?
Maybe try removing the 2nd line that says express();
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Welcome to API xyz!");
});
app.listen(3000, () => {
console.log("Listening on port 3000...");
});
I was facing the same issue and I usually start the server from VS code terminal. Before I could try the solutions given in a related question I tried running the server from the command prompt (Run as administrator) and it worked.
I use the command npm run start to start the server.
Hope it helps someone!
Related
I created a frontend app and now trying to incorporate backend into it.
ON the same frontend app i added an index.js file in the root directory, and installed express and required it in index.js file.
Very basic setup as below:
const express = require('express')
const cors = require('cors')
const port = process.env.PORT || 3001
const app = express()
app.get('/', (req, res) => {
res.send({
greetings: 'hi'
})
})
app.listen(port, () => {console.log(`Server on port ${port}`)})
Server is successfully on port 3001 as per my terminal, however, on localhost:3001 I'm not seeing any json response I set up in app.get.
It says Cannot GET / instead. When i inspected in devtool(Network) it says 404.
This seems a very straightforward setup, but what could've gone wrong here?
i just figured why. I installed nodemon but my “start” script is “node index.js”. Should’ve used “nodemon index.js”
Working now with nodemon index.ks
Your code is fine, There are no errors, I tested it and it works as expected.
However few things to note, Keep Backend in Seperate folder/dirctory unless required.
Coming back to your question, There are many possiblity such as some modules are not installed properly
try running following command
//this will install if any library is currupt or not installed properly
npm i
if it doesn't work then try clearing cache
Also keep in mind, In nodeJS dev server does not automatically refresh changes, you need to restart server to see changes or you can use dev dependancy called Nodemon (this will auto restart server on saving changes)
I am using Node/Express.js server on Windows Server 2012 R2 in the production and PM2.js to keep applications alive forever and to reload them without downtime. Since PM2 has limitations on Windows OS, I have chosen PM2-installer software to overcome them.
The server runs fine when I run with Node, so there is no issue with the server script.
node index.js
But, when I start the server with PM2, the server doesn't start and the status is "errored" (I had tried ecosystem file and cluster mode as well earlier with no luck).
pm2 start index.js
The logfile is empty, so there is no clue. Has anybody encountered this? Any solution?
Update 1:
I noticed the following error in service.log in C:\ProgramData\pm2\service
2021-03-23T23:13:56: PM2 log: App [server-plugin:0] starting in -fork mode-
2021-03-23T23:13:56: PM2 log: App [server-plugin:0] online
ERROR: 2021-03-23T23:13:56: PM2 error: Error: spawn node ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:269:19)
at onErrorNT (internal/child_process.js:465:16)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
3/23/2021, 11:13:56 PM: default/server-plugin#N/A - start - MANUAL
ERROR: 2021-03-23T23:13:56: PM2 error: Cancelling versioning data parsing
The error seems to indicate that it is not able to spawn node.js, but not sure why.
Update 2:
index.js is small test App directly in root folder and contains just this:
const fs = require('fs');
const express = require('express'),
https = require('https'),
const config = require('./config');
const hostname = config.hostname;
const port = config.port;
const app = express();
app.get("/*",(req, res, next) => {
console.log(req.headers);
res.send(`<html><body><h1>Hello ${req.params[0] || 'World'} from ${port} port!</h1></body></html>`);
});
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
}, app).listen(port, hostname, () => {
console.log(`Server running at https://${hostname}:${port}`);
There is an accompanying config.js, the SSL files and node_modules sub-folder in the root folder. That's all.
The solution for me was to abandon pm2-installer and use a Task scheduler approach. This solution was the savior. It works like a charm. An additional tip is to set the environment variable PM2_HOME to c:\users\<user>\.pm2 or something like that. This will help PM2 resurrect to pick up the dump file from this location. Also restart the machine for this scheme to work but if it is not possible to restart, run the created scheduled task manually.
I am building a website using node.js and mongoDB backend. Whenever I start running the server, frontend works completely fine but I am unable to connect to my database. Running mongod command always gives the message
{"t":{"$date":"2020-11-10T10:46:27.043+5:30"},"s:"I","c":"Network","id":23016,
"ctx":"listener","msg":"Waiting for connection","attr":{"port":27017,"ssl":"off"}}
I simultaneously executed npm start from the frontend and backend folders. The npm start from the backend folder gives
[nodemon] starting `node ./server.js`
Listening on port 8080
MongoDB connected
The npm start from the frontend folder gives
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.56.1:8080/
But whenever the open it, it gives
Cannot GET /
Is it because I couldn’t connect to the database? I’m fairly new to this. I can’t seem to understand the reason behind this. Can anyone please help me out?
Cannot GET /
means http://localhost:8080/ has no method defined in your app.
if you are using expressJs
in your server.js
add
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('No More error')
})
Here we are saying: send "No More error" whenever user opens "/" path.
i.e http://localhost:8080/ in your case.
This is my Node.js code:
// Using ES6 syntax is fine because we already have Babel to transpile code.
import express from 'express';
// Create an Express application.
const app = express();
// Define port number for the server.
const PORT = 400;
// When visitors make a GET request to address "/", specify the response.
app.get('/', (req, res) =>
res.send(`Node and Express server running on port ${PORT}`)
);
// Send message to the console to confirm that the server is running on the specified port.
app.listen(PORT, () =>
console.log(`Server running on port ${PORT}`)
);
When I use $ npm start, I get this:
> smr#1.0.0 start /Users/jaimemontoya/Desktop/SMR
> nodemon ./index.js --exec babel-node -e js
[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js
[nodemon] starting `babel-node ./index.js`
Server running on port 400
However, when I visit http://localhost:4000/ from a web browser, I see this:
This site can’t be reached
localhost refused to connect.
Try:
Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
Any ideas to make this work from a web browser?
UPDATE 1:
I meant http://localhost:400
I guess PORT 400 was not available for me. I used const PORT = 406; and now when I visit http://localhost:406/, it works, I get this message:
Node and Express server running on port 406
Note: Everything works perfectly on my localhost environment. When I git push heroku master I get a successful push/deploy. I check the Heroku Logs and I see this error:
[]: Stopping process with SIGKILL
[]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 120 seconds of launch
I have read many posts regarding this issue and the fix that I see is
app.set('port', (process.env.PORT || 4000));
This is not my fix since I am already doing this in my server code. Here is my server code:
var path = require('path');
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 4000));
app.use(express.static(__dirname + '/public'));
app.get('*', function response(req, res) {
res.render(path.join(__dirname, 'public/index.html'));
});
app.listen(app.get('port'), 'localhost', function onStart(err) {
if (err) {
console.log(err);
}
console.info('==> Listening on port %s.', app.get('port'));
});
NOTE: In the Heroku logs, ==> Listening on port %s. is printed and THEN the timeout happens after that (with no error). So it does get to the end of my server code without error and it prints the correct, random Heroku port.
Furthermore, webpack -p also creates my bundle.js correctly too.
My package.json has these two commands and they are executed without error:
"start": "NODE_ENV=production webpack -p && node server",
"postinstall": "bower install --force"
I am truly at a loss. Please help!
EDIT: I believe I have truly isolated the problem to my server.js file. I ended up doing webpack -p and pushed up the bundle.js file––essentially bypassing webpack on Heroku. I then do the simple npm start command (which is essentially just node server.js command) and my app still times out when trying to connect to the port.
WOW I figured it out. I had this line in my server:
app.listen(app.get('port'), 'localhost', function onStart(err) ....
I just needed to remove 'localhost' from the listen() function.