Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

req.body undefined on server side

I am working on app which uses node, express, mysql on server side. i have written serveral APIs on server.js file and when i am trying to access those using Postman then req.body is always undefined.

this is my server.js configuration.

var express = require('express');
var mysql = require('mysql');
var cors = require('cors');
var bodyParser = require('body-parser');
var wrench = require("wrench");
var fs = require('fs');
var path = require("path");
var mkdirp = require('mkdirp');
var walk = require('walk');
var fse = require('fs-extra');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var crypto = require('crypto');

app.use(cors());

app.use(bodyParser.urlencoded({limit: '50mb',extended: false}));
app.use(bodyParser.json({limit: '50mb'}));

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'pass',
    database: 'dbname'
});


connection.connect(function(err) {
    if (!err) {
        console.log("Database is connected ... \n\n");
    } else {
        console.log("Error connecting database ... \n\n");
    }
});

app.post('/urlreq', function(req, res){
    console.log(req.body);
}
app.listen(3000, function(){
    console.log("Rest Demo Listening on port 3000");
});

When i am trying send something in body in Postman then req.body is coming empty on server side.

like image 465
ashishkumar148 Avatar asked Sep 17 '15 12:09

ashishkumar148


People also ask

Why is req body undefined in Express?

Looks like the body-parser is no longer shipped with express. We may have to install it separately. var express = require('express') var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded app.

What is req body in Express?

The req. body object allows you to access data in a string or JSON object from the client side. You generally use the req. body object to receive data through POST and PUT requests in the Express server.

Is body parser included in Express?

The good news is that as of Express version 4.16+, their own body-parser implementation is now included in the default Express package so there is no need for you to download another dependency.


1 Answers

If you are sending multipart/form-data, it doesn't work because bodyparser doesn't handle this body type.

In this case adding the following line should fix it:

app.use(multipartMiddleware);

Form the docs:

multipart/form-data is the default encoding a web form uses to transfer data

like image 72
Oleg Avatar answered Nov 15 '22 04:11

Oleg