user10691457
user10691457

Reputation: 3

Request body is undefined

I use Express.js to make api.

The issue I am facing is access to body of request.

I can access to body when api is on server.js.

// backend/server.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/hello", (req, res) => {
  console.log(req.body);
});

postman post request to "/hello"

successfully working api

So this works fine. That's good. However, it does not work in this case.

// backend/server.js
app.use(require("./routes"));


// backend/routes/index.js
const express = require("express");
const router = express.Router();

router.use("/api", require("./api"));

module.exports = router;


// backend/routes/api/index.js
const express = require("express");
const router = express.Router();

router.use("/users", require("./users"));

module.exports = router;


// backend/routers/api/users.js
const router = require("express").Router();
router.post("/", auth.optional, (req, res, next) => {
    console.log("hello");
    console.log(req.body);
}

failed postman post request to "/api/users"

failed api

As you see, this api/users api runs fine, but I cannot access to body of request :(

Thank you for your help!

Upvotes: 0

Views: 312

Answers (2)

Golo Roden
Golo Roden

Reputation: 150614

In your first example, you import the body-parser with this line:

const bodyParser = require("body-parser");

And then you enable it:

app.use(bodyParser.json());

Both is required so that req.body exists, and contains what you expect – a parsed JSON object, taken from the request stream.

In your second example, both lines are missing, and hence req.body is undefined. You need to add them to your sample, then it will work.

Please note that req.body is not provided by Express itself, but is an extension provided by the body-parser middleware, hence you have to install it, import it, and actually use it.

For an example of how to use body-parser, see its documentation, either the section Express/Connect top-level generic or the section Express route-specific.

Upvotes: 1

Manoj Bhardwaj
Manoj Bhardwaj

Reputation: 858

You can try with body-parser or multer middleware may hope it will help you

  npm install body-parser --save

and then do this in your code

 var bodyParser = require('body-parser')
 var app = express()

parse application/x-www-form-urlencoded

 app.use(bodyParser.urlencoded({ extended: false }))

parse application/json

   app.use(bodyParser.json())

Or

If your body parser does not work then try with multer middleware it will work

var express = require('express')
var app = express()
var multer  = require('multer')
var upload = multer()

app.post('/profile', upload.none(), function (req, res, next) {
    // req.body contains the text fields
})

Upvotes: 0

Related Questions