'NodeJs how to parse post body sent from Postman
I'm having this simple NodeJs code to handle post request sent from any other origin like Postman
const http = require("http");
const { parse } = require("querystring");
const server = http.createServer(function (request, response) {
console.dir(request.param);
if (request.method === "POST") {
let body = "";
request.on("data", (chunk) => {
body += chunk.toString(); // convert Buffer to string
});
request.on("end", () => {
const result = parse(body);
console.log(result);
response.end("ok");
});
}
});
const port = 8080;
const host = "127.0.0.1";
server.listen(port, host);
When I send post request from Postman with form data like user:foo
I get it like this in the terminal
[Object: null prototype] {
'----------------------------908153651530187984286555\r\nContent-Disposition: form-data; name': '"user"\r\n\r\nfoo\r\n----------------------------908153651530187984286555--\r\n'
And when I run
console.log(result.user)
I get undefined
I changed the parsing body const result = parse(body);
into this
const result = JSON.parse(JSON.stringify(body))
And I got
----------------------------939697314758807513697606
Content-Disposition: form-data; name="user"
foo
----------------------------939697314758807513697606--
but still can't get result.user
How can I handle such data by converting it into an object and get the user like this result.user
Solution 1:[1]
If the data in your body is a JSON object, you can just remove the toString in chunks and replace the parse with JSON.parse, like so:
let body = "";
request.on("data", (chunk) => {
body += chunk; // convert Buffer to string
});
request.on("end", () => {
const result = JSON.parse(body);
console.log(result);
response.end("ok");
});
This will work OK if you sent the data from postman choosing "raw" and "JSON", sending an object as the following in the body:
{
"user": "john"
}
Your current approach, using querystring's parse method, should work well if the data was sent as "x-www-form-urlencoded".
In short, the solution would be to modify the Content-Type header of the request you are sending to your server.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |