简体   繁体   English

Node Express JSON 正文解析

[英]Node Express JSON Body Parsing

I'm a newbie in Express so for this issue I've researched quite bit but I cannot get it right.我是 Express 的新手,所以对于这个问题,我已经研究了很多,但我做错了。 So I need to pass an array like this ["1","2","3","4","5"] as a payload from Frontend, and in the Express I need to accept it and do stuff with it.所以我需要传递一个像这样的数组["1","2","3","4","5"]作为来自前端的有效负载,并且在 Express 中我需要接受它并用它做一些事情. So far, I can send it from Frontend and receive at Express but the content of what I receive does not look right.到目前为止,我可以从前端发送它并在 Express 接收,但我收到的内容看起来不正确。 In the Express I receive:在我收到的快递中:

POST / 200 3.239 ms - 97
{ '"1","2","3","4","5"': '' }

so I cannot do anything with this.所以我对此无能为力。 I tried to send an object called params and receive that to do something with that, that didn't work either.我试图发送一个名为 params 的 object 并接收它来处理它,但这也不起作用。

Frontend headers are like this前端标头是这样的

Request URL: http://localhost:5000/
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:5000
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 36
Content-Type: application/json; charset=utf-8
Date: Mon, 13 Dec 2021 23:06:58 GMT
ETag: W/"24-sEnfXlyl7goDTpCx3bZVIGauJsc"
Keep-Alive: timeout=5
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 21
Content-Type: application/x-www-form-urlencoded
DNT: 1
Host: localhost:5000
Origin: http://localhost:3000
Referer: http://localhost:3000/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36

Express setup that relates to this is like与此相关的快速设置就像

var express = require("express");
...
var app = express();
...
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.post("/", (req, res) => {
  res.json({ requestBody: req.body });
});

So how can I send as part of the body from frontend in ReactJS an array ["1","2","3","4","5"] then accept that as array in express and do stuff with it?那么如何从 ReactJS 中的前端发送一个数组["1","2","3","4","5"]作为正文的一部分,然后接受它作为快递数组并用它做些什么呢?

What you show as the request:您显示为请求的内容:

POST / 200 3.239 ms - 97
{ '"1","2","3","4","5"': '' }

And, the headers you show as:而且,您显示为的标题:

Content-Type: application/x-www-form-urlencoded

Do not match.不符合。 Your data is being sent as plain text.您的数据以纯文本形式发送。 It's not application/json or application/x-www-form-urlencoded so you don't have a body-parser installed for it so Express doesn't know what to do with it.它不是application/jsonapplication/x-www-form-urlencoded所以你没有为它安装 body-parser 所以 Express 不知道如何处理它。 In fact, Express doesn't even read it, it just stays in the incoming stream.事实上,Express 甚至没有读取它,它只是停留在传入的 stream 中。

You don't show the client-side code, but the client needs to make the content-type and the encoding of the body content you send with the POST actually match.您不显示客户端代码,但客户端需要使您使用 POST 发送的正文内容的content-type和编码实际匹配。 Then, you need a body-parser for that content-type on the Express side of things.然后,您需要在 Express 方面为该content-type提供一个正文解析器。

Since this is meant to be an array of data, I would suggest using JSON and sending application/json encoded data.由于这是一个数据数组,我建议使用 JSON 并发送应用程序/json 编码数据。 Then, your existing express.json() middleware will read and parse it for you and you can read the data in req.body .然后,您现有的express.json()中间件将为您读取和解析它,您可以读取req.body中的数据。

If you want help fixing the client-side, then show us the client-side code that is sending this.如果您需要帮助修复客户端,请向我们展示发送此内容的客户端代码。

For example, if you were sending this from the client with fetch() , here's an example right from the MDN doc for fetch() :例如,如果您使用fetch()从客户端发送此信息,则以下是MDN 文档fetch()的示例:

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `data.json()` call
});

You should NOT send an object called params .不应发送名为params的 object 。 Since its POST request, you should send the array as an property of the request body .由于它的 POST 请求,您应该将数组作为请求的属性发送。 Then it will be available in the req.body property in the Express app.然后它将在 Express 应用程序的req.body属性中可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM