我简化了代码,以除去错误以外的所有内容。该代码在我的服务器上工作正常,但是在本地环境中产生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> 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>
很奇怪!有什么想法吗?
答案 0 :(得分:0)
这应该可以解决您的问题。
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));