简体   繁体   中英

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. 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. So far, I can send it from Frontend and receive at Express but the content of what I receive does not look right. 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.

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?

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. In fact, Express doesn't even read it, it just stays in the incoming 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. Then, you need a body-parser for that content-type on the Express side of things.

Since this is meant to be an array of data, I would suggest using JSON and sending application/json encoded data. Then, your existing express.json() middleware will read and parse it for you and you can read the data in 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() :

// 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 . Since its POST request, you should send the array as an property of the request body . Then it will be available in the req.body property in the Express app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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