body-parser,JSON位置的意外标记u

问题描述 投票:0回答:2

我正在使用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.js json express body-parser
2个回答
0
投票

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

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


0
投票

你需要curl -d "{"user":"Someone"}" -H "Content-Type: application/json" --url http://localhost:8080;有时Curl不会解析单引号。

© www.soinside.com 2019 - 2024. All rights reserved.