jm123456
jm123456

Reputation: 625

Express port is undefined when running with "node ."

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.com/community/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.

Upvotes: 2

Views: 7377

Answers (3)

Yilmaz
Yilmaz

Reputation: 49293

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}`)})

Upvotes: 0

Mukul Chavan
Mukul Chavan

Reputation: 1

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}`);
});

Upvotes: -1

Jack Yu
Jack Yu

Reputation: 2425

app.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}`);
});

Upvotes: 8

Related Questions