javascript Node.js express.json 中间件未按预期解析请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21661047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:25:15  来源:igfitidea点击:

Node.js express.json middleware not parsing request as expected

javascriptjsonnode.jsexpress

提问by akaphenom

I have a simple cURL (i think this is right) that posts a small JSON object to my express server:

我有一个简单的 cURL(我认为这是正确的),它将一个小的 JSON 对象发布到我的快速服务器:

curl -d "{'test': 'this'}" localhost:3000/rest/user/authenticate

I have express set up as:

我已将快递设置为:

// set up body parsing in express  to be able  to get parse JSON posts
server.use(express.json());
server.use(express.urlencoded());

and have handler that accepts the route:

并有接受路线的处理程序:

JSON = require('JSON')
module.exports = {
    authenticateUser: function create(req, res){
        var postedObject = req.body
        console.log(postedObject)
        res.send('Handle Post: authenticateUser');
    }
}

the handler is getting called, but it is logging the JSON body unexpectedly:

处理程序正在被调用,但它意外地记录了 JSON 正文:

{ '{\'test\': \'this\'}': '' }

So my entire object looks to be the name side of a JSON Name:Value pair object. no matter what I post it seems to be appending the value side. Unless I do something like this:

所以我的整个对象看起来是 JSON Name:Value 对对象的名称端。无论我发布什么,它似乎都在附加价值方面。除非我做这样的事情:

curl -d "a=a" localhost:3000/rest/user/authenticate

which logs:

其中日志:

{'a':'a'}

so have i not set the right headers? Configured express wrong? I plan on digging through the express code, but wondered if somebody might know before I find the solution. Either way having a searchable/indexed answer to this on the web will be nice.

所以我没有设置正确的标题吗?配置express错了吗?我计划深入研究快速代码,但想知道在我找到解决方案之前是否有人可能知道。无论哪种方式,在网络上对此都有一个可搜索/索引的答案都会很好。

update 1

更新 1

ok I need to add the header to the cURL

好的,我需要将标题添加到 cURL

curl -H "Content-Type: application/json" -d "{'test': 'this'}" localhost:3000/rest/user/authenticate

which gives the error:

这给出了错误:

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)

OR curl -H "Content-Type: application/json" -d "{test: 'this'}" localhost:3000/rest/user/authenticate

或 curl -H "Content-Type: application/json" -d "{test: 'this'}" localhost:3000/rest/user/authenticate

which gives the error:

这给出了错误:

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)

update 2

更新 2

in the file connect/lib/middleware/json.js

在文件 connect/lib/middleware/json.js

this line seems to be the one causing issues

这条线似乎是导致问题的原因

req.body = JSON.parse(buf, options.reviver);

update 3

更新 3

I really think it is my cURL

我真的认为这是我的 cURL

buf= JSON.stringify({test: 'This'});
console.log(buf)
req.body = JSON.parse(buf, options.reviver);

works logging first {"test":"this"}

首先记录工作 {"test":"this"}

and then in my handler:

然后在我的处理程序中:

----------------------
{ test: 'this' }
----------------------

回答by Oleg

1) JSON middleware only works if the request has Content-Type: application/jsonheader.
2) Valid JSON should contain ", not '.
So it should be '{"test": "this"}'instead of "{'test': 'this'}"

1) JSON 中间件仅在请求具有Content-Type: application/json标头时才有效。
2) 有效的 JSON 应该包含",而不是'.
所以它应该'{"test": "this"}'代替"{'test': 'this'}"

Try this command:

试试这个命令:

curl -d '{"test": "this"}' -H "Content-Type: application/json" localhost:3000/rest/user/authenticate

回答by akaphenom

THe answer has two pieces

答案有两部分

  1. add the content header
  2. on windows go through the pain of passing the json correctly, cURL on my windows machine doesn't deal with interchanging the single and double quotes , therefore the proper cURL is

    curl -H "Content-Type: application/json" -d "{"""test""": """this"""}" localhost:3000/rest/user/authenticate

  1. 添加内容标题
  2. 在 Windows 上经历了正确传递 json 的痛苦,我的 Windows 机器上的 cURL 不处理交换单引号和双引号,因此正确的 cURL 是

    curl -H "Content-Type: application/json" -d "{"""test""": """this"""}" localhost:3000/rest/user/authenticate

Yup, inside of the data parameter, you need to use three double quotes to send a single double quote to the server.

是的,在 data 参数内部,您需要使用三个双引号将单个双引号发送到服务器。

Accepting zub's answer, because he is correct. I was trying a bunch of things to get around windows here.

接受zub的回答,因为他是对的。我尝试了很多方法来绕过这里的窗户。

回答by Slaters

For those who use postman like me just try to send the request as POST>>RAW and create your Json to do the post, in my test i have created a simple json like this and works:

对于像我这样使用邮递员的人,只需尝试将请求作为 POST>>RAW 发送并创建您的 Json 来完成发布,在我的测试中,我创建了一个像这样的简单 json 并且可以正常工作:

{ "name": "test" }

{“名称”:“测试”}

Using form-data or x-www-form-urlencoded it doesn't work.

使用 form-data 或 x-www-form-urlencoded 它不起作用。

回答by Yuanpeng.Zheng

Under Windows cmd:

在 Windows cmd 下:

curl -H "Content-Type: application/json" -d "{"""test""": """this"""}" localhost:3000/rest/user/authenticate

or use cygwin:

或使用 cygwin:

curl -H "Content-Type: application/json" -d '{"test": "this"}' localhost:3000/rest/user/authenticate 

My 2 cents

我的 2 美分