Search code examples
expresspostpostmanbody-parser

BodyParser causes all API requests to hang. Even basic GET requests


As the title says, I simply don't understand what is going on here. Once I include the app.use(bodyParser.json) line, Postman just keeps handing on any request I make. I lost a good portion of the day thinking I messed up my routes.

I narrowed it down to it in this little testing file:

const express = require("express")
const bodyParser = require("body-parser")
const env = require("dotenv");
const app = express()

env.config();
app.use(bodyParser.json);

app.get("/", (req, res) => {
    res.status(200).json({
        message:"Hello World"
    })
});

app.post("/data", (req, res) => {
    req.status(200).json({
        message: req.body
    })
});

app.listen(process.env.PORT, ()=>{
    console.log(`Server listening at port ${process.env.PORT}`);
})

Can anyone tell me what is happening and how I can fix it?


Solution

  • You need to call JSON body parser as a function (with brackets):

    app.use(bodyParser.json());
    

    There is another bug in the post method "data", You should call status from "res" object:

    app.post("/data", (req, res) => {
        res.status(200).json({
            message: req.body
        })
    });