app.use(express.json())提供了意外的令牌错误

时间:2019-01-08 08:11:21

标签: json express

我简化了代码,以除去错误以外的所有内容。该代码在我的服务器上工作正常,但是在本地环境中产生unexpected token错误。

此代码有效:

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

此代码给出错误:

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

我正在使用邮递员进行测试。完整的错误是:

<!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>

很奇怪!有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我猜您正在使用Express版本> 4.1

这应该可以解决您的问题。

const bodyParser = require('body-parser'); 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));