【问题标题】:body-parser, Unexpected token u in JSON at position正文解析器,JSON 中的意外标记 u 在位置
【发布时间】:2019-10-06 02:39:16
【问题描述】:

我正在使用 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


    【解决方案1】:

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

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

    【讨论】:

    • 因为我在命令行中执行此操作,所以我只是尝试了curl --header "Content-Type: application/json" \ --request POST \ --data '{"user":"Someone"}' \ http://localhost:8080/,但我得到了几个错误
    • curl: (6) Could not resolve host: --request curl: (6) Could not resolve host: POST curl: (6) Could not resolve host: --data curl: (3) Port number ended with '"' curl: (1) Protocol " http" not supported or disabled in libcurl
    • 试试:curl --header "Content-Type: application/json" --request POST --data '{"user":"Someone"}' http://localhost:8080/
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 2019-08-30
      • 2019-08-10
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 2022-07-31
      • 1970-01-01
      • 2016-09-04
      相关资源
      最近更新 更多