Issue
I have simplified my code to strip away everything but the error. The code works fine on my server but produces an unexpected token
error in the local environment.
This code works:
const express = require("express");
app = express();
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
This code gives the error:
const express = require("express");
app = express();
app.use(express.json());
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
I am using postman for testing. The full error is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>SyntaxError: Unexpected token
in JSON at position 46
<br> at JSON.parse (<anonymous>)
<br> at parse (C:\WebDev\MongoDB\node_modules\body-parser\lib\types\json.js:89:19)
<br> at C:\WebDev\MongoDB\node_modules\body-parser\lib\read.js:121:18
<br> at invokeCallback (C:\WebDev\MongoDB\node_modules\raw-body\index.js:224:16)
<br> at done (C:\WebDev\MongoDB\node_modules\raw-body\index.js:213:7)
<br> at IncomingMessage.onEnd (C:\WebDev\MongoDB\node_modules\raw-body\index.js:273:7)
<br> at IncomingMessage.emit (events.js:182:13)
<br> at endReadableNT (_stream_readable.js:1094:12)
<br> at process._tickCallback (internal/process/next_tick.js:63:19)
</pre>
</body>
</html>
Weird right! Any ideas??
Solution
i guess you are using express version > 4.1
this should solve ur problem.
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));