首页 > 解决方案 > 正文解析器,JSON 中的意外标记 u 在位置

问题描述

我正在使用 body-parser 来获取 POST 请求的正文。我的index.js文件如下所示:

var express = require('express');
var app = express();
var bodyParser  = require('body-parser');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());
app.use(express.json());

app.post('/', function(request, response){
    console.log(request.body);
    res.send("test");
});

app.get('/', function(req, res) {
  res.send('Hello World!');
});



app.listen(8080, function() {
  console.log('Example app listening on port 8080!');
});

当我启动我的 docker 时,我得到了预期的监听消息。

当我运行命令时:

curl -d {"user":"Someone"} -H "Content-Type: application/json" --url http://localhost:8080

我得到错误:

Unexpected token u in JSON at position 1
at JSON.parse (<anonymous>)

我很困惑,因为我没有在任何地方直接调用 json.parse

标签: node.jsjsonexpressbody-parser

解决方案


问题可能出在请求中。正文应该是一个字符串:

curl -X POST -H "Content-Type: application/json" -d '{"message": "foo"}' http://localhost:8080/messages


推荐阅读