[Fixed] app.use(express.json()) giving an unexpected token error

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> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)
            <br> &nbsp; &nbsp;at parse (C:\WebDev\MongoDB\node_modules\body-parser\lib\types\json.js:89:19)
            <br> &nbsp; &nbsp;at C:\WebDev\MongoDB\node_modules\body-parser\lib\read.js:121:18
            <br> &nbsp; &nbsp;at invokeCallback (C:\WebDev\MongoDB\node_modules\raw-body\index.js:224:16)
            <br> &nbsp; &nbsp;at done (C:\WebDev\MongoDB\node_modules\raw-body\index.js:213:7)
            <br> &nbsp; &nbsp;at IncomingMessage.onEnd (C:\WebDev\MongoDB\node_modules\raw-body\index.js:273:7)
            <br> &nbsp; &nbsp;at IncomingMessage.emit (events.js:182:13)
            <br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js:1094:12)
            <br> &nbsp; &nbsp;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 }));

Leave a Reply

(*) Required, Your email will not be published