Deep Kakkar
Deep Kakkar

Reputation: 6307

How to get request body in Node JS middle ware from multi-part form data?

I know it is easy to get the requested body using as follows:

app.post('/api', (req, res) => { conosle.log(req.body); })

But my question is different from above. Here is my index.js file (entry file).

const express = require('express');
const app = express();

const config = require('./config/config.js');

app.use(express.raw());
app.use(express.urlencoded({ extended: true }));

app.use((req, res, next) => {

  console.log(req.body); **// here I am not getting req.body**

  const routes_handler = require('./routes/index.js')(app, express, req);
  next();
});


app.listen(config.SERVER.PORT, () => {
  console.log("Server running at Port " + config.SERVER.PORT);
});

FYI, using the postman, I am passing request as form-data. and in the form, there is also a field as file type(picture). In handling the API part, I am using multer and also getting req.body as per required.

But I just want to know how can I get req.body in middleware block i.e. in

 app.use((req, res, next) => {//HERE req.body })

Here is my POSTMAN simple request as follows:

enter image description here

Upvotes: 3

Views: 7158

Answers (3)

Chuong Tran
Chuong Tran

Reputation: 3431

Try to using body-parser. You can find an example code here from express.js

const app = require('express')()
const bodyParser = require('body-parser')
const multer = require('multer')

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

app.use(multer.array(), (req, res, next) => {

  console.log(req.body);

  const routes_handler = require('./routes/index.js')(app, express, req);
  next();
});

Upvotes: 1

Waleed Shafiq
Waleed Shafiq

Reputation: 414

simple make a middleware function like this :

const middleware = (req,res,next) =>{
     console.log(req.body);
     // all your multer logic here
}

and use it before your post request route like this..

app.post('/' , middleware , (req,res,next) =>{
// all your api logic here 
});

as body is only availabe in certain types of http requests including post ,put and not available in get requests so you wont get your console.log() in those requests.

Upvotes: -1

Mahesh Bhatnagar
Mahesh Bhatnagar

Reputation: 1080

Please use multer for getting form data

var multer = require('multer');
var upload = multer();

app.use(upload.array()); 

Upvotes: 1

Related Questions