Express POST Request SyntaxError: Unexpected token o in JSON at position 1

时间:2020-12-20 01:03:15

标签: node.js json express

我正在尝试使用 node 和 express 获取 POST 请求的 JSON 请求正文。但是,我从 express 收到此错误:

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at parse (C:\Users\Bradley\Desktop\test\node_modules\body-parser\lib\types\json.js:89:19)
    at C:\Users\Bradley\Desktop\test\node_modules\body-parser\lib\read.js:121:18
    at invokeCallback (C:\Users\Bradley\Desktop\test\node_modules\raw-body\index.js:224:16)
    at done (C:\Users\Bradley\Desktop\test\node_modules\raw-body\index.js:213:7)
    at IncomingMessage.onEnd (C:\Users\Bradley\Desktop\test\node_modules\raw-body\index.js:273:7)
    at IncomingMessage.emit (events.js:323:22)
    at endReadableNT (_stream_readable.js:1204:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)

这是我正在运行的所有代码:

const express = require('express');
const app = express();
const port = 5680;

app.use(express.json());

app.listen(port, () => {
    console.log(`app listening at http://localhost:${port}`)
});

app.post('/api', (req, res) => {
   console.log(JSON.stringify(req.body));
   return res.sendStatus(200);
});

为了触发我提交请求的错误:

fetch('http://localhost:5680/api', {
        method: 'POST',
        headers: {'Content-type': 'application/json; charset=UTF-8'},
        body: {"key": "value"}
    }).then(response => console.log(response));

似乎 body-parser 对 JSON 进行了双重解析,但我不知道为什么。

1 个答案:

答案 0 :(得分:1)

问题在于请求。正文应该是一个字符串,所以完整的请求是:

fetch('http://localhost:5680/api', {
        method: 'POST',
        headers: {'Content-type': 'application/json; charset=UTF-8'},
        body: '{"key": "value"}'
    }).then(response => console.log(response));