'Postman unable to send request body to express application
I am making a simple post request as follows:
app.post('/', (req, res) => {
return res.status(200).json(req.body)
})
When I give a post request through postman, nothing comes up its just an empty {}.
Here is server.js:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const app = express();
// Bodyparser middleware
const users = require("./routes/api/users");
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server up and running on port ${port}`));
app.post('/', (req, res) => {
return res.status(200).json(req.body)
})
Solution 1:[1]
Your POST body is empty. You are are using query params in your post request. Click on the Body tab in Postman and add your request body there.
{
"name": "abcxyz",
"age" : 92
}
Solution 2:[2]
You are using query parameters
?name=abcxyz&age=69
In your example you can access these in express by using req.query:
app.post('/', (req, res) => {
return res.status(200).json(req.query)
})
Solution 3:[3]
In requests there are a couple of ways to pass data, popular two are:
Query params (the ones you passed through Postman) - these parameters are added to your URL while making the request to the server(making it fit for some use cases and not so much for others), you can access those in the backend using req.query.
app.post('/', (req, res) => { return res.status(200).json(req.query) });Request Body (the way you're trying to access currently) - to pass those through Postman you'd normally want to pass in JSON format on the "body" tab. you can access those using req.body in your backend.
app.post('/', (req, res) => { return res.status(200).json(req.body) });
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 | Shaun Spinelli |
| Solution 2 | |
| Solution 3 | oriel9p |

