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)
})
And here is the Postman snippet:
CodePudding user response:
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
}
CodePudding user response:
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)
})