1
votes

I'm trying to do a POST request using raw json.

In the Body tab I have "raw" selected with this body:

{
"name": "book"
}

On the Node js side I'm doing res.send(JSON.stringify(req.body))

router.post('/', (req, res, next) => {
  res.send(JSON.stringify(req.body));
}

And in POSTMAN response I receive:

{"{\n\"name\": \"book\"\n}":""}

When expected something like

{"name":"book"}

Have no idea - where could be a reason for it?

4

4 Answers

1
votes

You'll need to use the Express JSON body parser, install using

npm install body-parser; 

Then:

const bodyParser = require('body-parser');
app.use(bodyParser.json());

Once you do this, the JSON data will be parsed correctly and when you send it back it will render correctly.

Also make sure you have your Content-Type header set to "application/json" in your Postman request (go to "Headers" and add a new "Content-Type" header with value "application/json")

Here's a simple express app that will echo any JSON POST:

const express = require("express");
const port = 3000;
const app = express();
const bodyParser = require('body-parser')

app.use(bodyParser.json());

app.post('/', (req, res, next) => {
    console.log("Body: ", req.body);
    res.send(JSON.stringify(req.body));
})

app.listen(port);
console.log(`Serving at http://localhost:${port}`);
0
votes

Looks to me like its not a fault of Postman, but your NodeJS service is applying JSON.stringify twice?

Can you log the response type from the server to console to check whether its already json content or not?

0
votes

try with hard coded json response and then with dynamic variable

res.json({"name":"book"});
0
votes

If you're on Express v4.16.0 onwards, try to add this line before app.listen():

app.use(express.json());

    This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.