我有一个简单的 cURL(我认为这是正确的),它将一个小的 JSON 对象发布到我的快速服务器:
curl -d "{'test': 'this'}" localhost:3000/rest/user/authenticate
我的 express 设置为:
// set up body parsing in express to be able to get parse JSON posts
server.use(express.json());
server.use(express.urlencoded());
并有接受路由的处理程序:
JSON = require('JSON')
module.exports = {
authenticateUser: function create(req, res){
var postedObject = req.body
console.log(postedObject)
res.send('Handle Post: authenticateUser');
}
}
处理程序被调用,但它意外地记录了 JSON 正文:
{ '{\'test\': \'this\'}': '' }
所以我的整个对象看起来是 JSON 名称:值对对象的名称端。无论我发布什么,它似乎都在附加值(value)方面。除非我这样做:
curl -d "a=a" localhost:3000/rest/user/authenticate
哪些日志:
{'a':'a'}
所以我没有设置正确的标题吗?配置 express 错了?我计划挖掘快速代码,但想知道在我找到解决方案之前是否有人知道。无论哪种方式,在网络上都有一个可搜索/索引的答案都会很好。
更新 1
好的,我需要将标题添加到 cURL
curl -H "Content-Type: application/json" -d "{'test': 'this'}" localhost:3000/rest/user/authenticate
给出错误:
Parsing: {'test': 'this'}
SyntaxError: Unexpected token '
at Object.parse (native)
at C:\blah\node_modules\express\node_modules\connect\lib\middleware\json.js:86:19
at IncomingMessage.onEnd (C:blah\node_modules\express\node_modules\connect\node_modules\raw-body\index.js:109:7)
at IncomingMessage.g (events.js:180:16)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
或 curl -H "Content-Type: application/json"-d "{test: 'this'}"localhost:3000/rest/user/authenticate
给出错误:
Parsing: {test: 'this'}
SyntaxError: Unexpected token t
at Object.parse (native)
at C:\blah\node_modules\express\node_modules\connect\lib\middleware\json.js:86:19
at IncomingMessage.onEnd (C:blah\node_modules\express\node_modules\connect\node_modules\raw-body\index.js:109:7)
at IncomingMessage.g (events.js:180:16)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
更新 2
在文件connect/lib/middleware/json.js中
这一行似乎是导致问题的原因
req.body = JSON.parse(buf, options.reviver);
更新 3
我真的认为这是我的 cURL
buf= JSON.stringify({test: 'This'});
console.log(buf)
req.body = JSON.parse(buf, options.reviver);
首先工作记录 {"test":"this"}
然后在我的处理程序中:
----------------------
{ test: 'this' }
----------------------
最佳答案
1) JSON 中间件仅在请求具有 Content-Type: application/json
header 时才有效。
2) 有效的 JSON 应该包含 "
,而不是 '
。
所以应该是 '{"test": "this"}'
而不是 "{'test': 'this'}"
试试这个命令:
curl -d '{"test": "this"}' -H "Content-Type: application/json" localhost:3000/rest/user/authenticate
关于javascript - Node.js express.json 中间件未按预期解析请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21661047/