Bodunde Adebiyi Bodunde Adebiyi - 7 months ago 14
Javascript Question

http service in angular sends post data as the key of the request body with no value

I'm building an angular application and I'm using the $http service. When I send a post request to my node api my post data appears as the key to req.body with an empty string as the value.

On logging my req.body and req.headers on my server side I get this

{ '{"username":"niccolo","password":"pass123"}': '' } //req.body
{ host: 'localhost:3000',
connection: 'keep-alive',
'content-length': '43',
accept: '*/*',
origin: 'http://localhost:3000',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',
'content-type': 'application/x-www-form-urlencoded',
referer: 'http://localhost:3000/login',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en-US,en;q=0.8' } //req.header


Below is the service that makes the request

angular.module('dochub.services').service('Auth', ['$http', '$rootScope',function($http, $rootScope){
this.login = function(user, cb){
config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*'
}
}
req = $http.post($rootScope.apiBaseUrl+'users/login', user, config);
req.success(function(data){
cb(data);
})
}
this.logout = function(cb){
cb(data);
}
}]);


Also when I made a request to that endpoint using PostMan it worked properly so I guess the problem has to be with my angular code

Answer

If you are using body-parser with express

Try this

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

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

app.use(parser.json());

You can use the default Content-Type with $http

'Content-Type: application/json'
Comments