tendinitis
tendinitis

Reputation: 1007

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)
})

And here is the Postman snippet: enter image description here

Upvotes: 1

Views: 1464

Answers (3)

oriel9p
oriel9p

Reputation: 336

In requests there are a couple of ways to pass data, popular two are:

  1. 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)
    });
    
  2. 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)
     });
    

Upvotes: 0

derpdewp
derpdewp

Reputation: 207

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)
})

Upvotes: 1

Shaun Spinelli
Shaun Spinelli

Reputation: 21

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
}

Upvotes: 2

Related Questions