Satish Pahuja Satish Pahuja - 1 year ago 98
Javascript Question

express POST req.body parser is empty

I saw similar issues on Stack Overflow and found solution to use of:

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


But while printing log
req.body
is blank.

app.js contents:

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

// Define the port to run on
app.set('port', 8888);

app.use(express.static(path.join(__dirname, '/webapp/public')));

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

app.post('/getsolution', function (req, res) {
console.log("request body is",req.body); //----req.body is blank here
});


Post request code from angular is as below

var parameters = JSON.stringify({ "urlPath": $location.path()});
$http.post('http://localhost:8888/getsolution/', parameters)
.then(function (response) {
if (response.data == "") {
$window.location.href = 'http://localhost:8888/';
} else {
$scope.puzzle = response.data;
$scope.puzzleSolution = response.data.solution;
}
}).catch(function onError(response) {
$window.location.href = 'http://localhost:8888/';
});


Log printing on console is


request body is {}


When using with below snippet it is not working



var app = angular.module('puzzleappsolution', [], function ($locationProvider) {
$locationProvider.html5Mode(true);
});//----->It is now working


But when using below it is working



var app = angular.module('puzzleappsolution', []);

Answer Source

Add Content-Type header to your request in angular:

$http.post('http://localhost:8888/getsolution/', parameters, {
    headers: {
        'Content-Type': 'application/json'
    }
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download