Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: Unexpected token const

Tags:

node.js

I am creating a web server that will allow users make a request for fortunes, and get the data which I specified in my fortunes.json file. I am using express in node to do this.

I start my server this way npm run dev, however when I do so, I get the following error:

SyntaxError: Unexpected token const
    at Module._compile (internal/modules/cjs/loader.js:720:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:643:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:839:10)
    at internal/main/run_main_module.js:17:11

Does anybody have an idea what I am doing wrong, my syntax, and packages.json file, etc. all seems to be fine but I am still getting this.

I am expecting to see "server listening on port 3000" when I run the server however I get a token error.

const express = require('express');

const port = 3000,

const app = express();

app.get('/fortunes', (req,res) => {
    console.log('requesting fortunes');

});
app.listen(port, () => console.log('Listening on port ${port}'));
like image 294
Laurens Avatar asked Sep 01 '25 15:09

Laurens


1 Answers

You have two issues in your code.

1 . when you are initializing variable:

As you have put ',' (comma) thus you cannot specify its declaration again.

your code

   const port = 3000,
   const app = express();

Do like this :

  const port = 3000,
   app = express();

or use this :

 const port = 3000;
 const app = express();
  1. When using string template use `(backtick).
app.listen(port, () => console.log(`Listening on port ${port}`));

Try below Code:

const express = require('express');

const port = 3000,

app = express();

app.get('/fortunes', (req,res) => {
    console.log('requesting fortunes');

});
app.listen(port, () => console.log(`Listening on port ${port}`));
like image 115
Saurabh Bishnoi Avatar answered Sep 06 '25 21:09

Saurabh Bishnoi