I've been following the tutorial here and it's been fine up until the part where I had to run the server:
If I try and run the code below I get server is listening on undefined
const app = express();
const port = 8080;
app.get("/", (req, res) => {
res.send("Hello");
})
app.listen((port, err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
I even tried to set the port beforehand using app.set('port', port);
const app = express();
const port = 8080;
app.set('port', port);
app.get("/", (req, res) => {
res.send("Hello");
})
app.listen((port, err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
But the same thing happens.
I've been following the tutorial here and it's been fine up until the part where I had to run the server: https://www.digitalocean./munity/tutorials/setting-up-a-node-project-with-typescript
If I try and run the code below I get server is listening on undefined
const app = express();
const port = 8080;
app.get("/", (req, res) => {
res.send("Hello");
})
app.listen((port, err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
I even tried to set the port beforehand using app.set('port', port);
const app = express();
const port = 8080;
app.set('port', port);
app.get("/", (req, res) => {
res.send("Hello");
})
app.listen((port, err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
But the same thing happens.
Share Improve this question asked Dec 22, 2020 at 14:28 jm123456jm123456 6351 gold badge10 silver badges22 bronze badges3 Answers
Reset to default 8app.listen
accept two arguments, first one is port, second is callback.
Change it to following code.
app.listen(port, (err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
This is an example in tutorial. He ignores the ()
in function from (err) => {}
to err => {}
, both work.
app.listen(port, err => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
app.listen(port, (err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
this is wrong, because app.listen()
does not take "err". Its callback does not take any argument. If you were using typescript, you would get warning. If app.listen()
gets an error, it will not run and client will get 404 error. it is just like this:
app.listen(port,()=>{
console.log(`server is listening on ${port}`)})
change it with following code , first params will be port
app.listen(port, err) => {
if (err)return console.error(err);
return console.log(`server is listening on ${port}`);
});