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)
})
3
Answers
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.
You are using query parameters
In your example you can access these in express by using req.query:
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.
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.