javascriptnode.jsjsonexpressjsonparser

NodeJS - Express can't read application/json data


I'm trying to setup a NodeJS express JSON REST API for the first time, but I'm facing some troubles while trying to retrieve the JSON data coming from the requests (both GET and POST requests)

Here's the code:

var bodyParser = require("body-parser");
const express = require("express");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

app.get("/prova", (req, res)=>{
    console.log(req.headers["content-type"]);
    console.log(req.body);
    res.status(200).json(req.body);
});

Here's the console.log(); When trying to make a request with Postman with some parameters:

application/json
{}

And here are the Postman request's details

enter image description here


Solution

  • You should avoid sending body with HTTP GET methods as per MDN web docs. As for the shown GET method this line res.status(200).json(req.body); is giving you an empty object, change it for example to res.status(200).json({message:"Hello world!"}); to see the message. For the POST method you can access the body as you do with req.body.