req.body undefined on server side
Asked Answered
D

3

6

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.

Dickerson answered 17/9, 2015 at 12:44 Comment(3)
Are you sending multipart/form-data request? If so, it doesn't work because bodyparser doesn't handle this body typeAustroasiatic
Typo in app.listem change it to app.listenCornstarch
@ Curious i am not using multipart for form-data justing sending form data as object.Dickerson
A
3

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

Austroasiatic answered 17/9, 2015 at 14:25 Comment(0)
V
0

You can use as a middleware also. Also listen on a port. add following lines in your code -

var app = express();

app.use(function(req, res, next) {      
  console.log('Current User:', req.body);
  next();
});

app.post('/url', function(req,res){
    console.log(req.body)
});


app.listen(3000, function(){
   console.log('Express server listening on port 3000');
});
Valvate answered 17/9, 2015 at 12:58 Comment(1)
Yeah, but still same prob. is coming.Dickerson
K
0

Try add:

var express = require('express');
var app = express();
[...]

// Last stack
app.listen(3000, function(){ 
    console.log("Rest Demo Listening on port 3000"); 
});
Kkt answered 17/9, 2015 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.