正文解析器,位置 JSON 中的意外标记 u
body-parser, Unexpected token u in JSON at position
我正在使用 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
你需要
curl -d "{"user":"Someone"}" -H "Content-Type: application/json" --url http://localhost:8080;
有时 Curl 不解析单引号。
可能问题出在请求中。正文应该是一个字符串:
curl -X POST -H "Content-Type: application/json" -d '{"message": "foo"}' http://localhost:8080/messages
我正在使用 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
你需要
curl -d "{"user":"Someone"}" -H "Content-Type: application/json" --url http://localhost:8080;
有时 Curl 不解析单引号。
可能问题出在请求中。正文应该是一个字符串:
curl -X POST -H "Content-Type: application/json" -d '{"message": "foo"}' http://localhost:8080/messages