node.js - 正文解析器,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
解决方案
问题可能出在请求中。正文应该是一个字符串:
curl -X POST -H "Content-Type: application/json" -d '{"message": "foo"}' http://localhost:8080/messages
推荐阅读
- python - 在python中比较单个元素和数组时选择最大值
- python - 列表中的重复项 - 在第二项之后插入输出
- c# - API 返回图片
- hyperledger-fabric - Hyperledger 结构加入通道:错误:2 未知:访问被拒绝:通道 [] 创建者组织 [Org1MSP]
- php - 尝试使用作曲家安装 guzzle 时如何解决错误?
- jenkins - 启用“块构建直到完成”选项触发远程作业时,Jenkins Pipeline 失败
- c - 当我尝试将其更改为反向字母顺序时,排序功能会中断?
- javascript - 从 php 文件重定向到本地 HTML 文件
- azure-cosmosdb - 如何清空集合,重建索引,然后再次填充集合?
- c# - 如何使用 LINQ 从 DataTable 中获取分组的字段数组