Xsmael
Xsmael

Reputation: 3932

POSTing data from angularJS to Express using $http

I'm trying so send some json data from angularjs to express/nodejs

AngularJS code:

$http({
      method: 'POST',
      url: 'http://localhost:8000/api/auth',
      data: {
         name: user,
         password: passwd
      },
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
      }
   })
   .success(function(data, status, headers, config) {
      $scope.loginStatus = data;
   })
   .error(function(data, status, headers, config) {
      $scope.lloginStatusogin = data;
   });

ExpressJS code:

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


var config = require('./config'); // get our config file


var port = process.env.PORT || 8000; // used to create, sign, and verify tokens

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

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

var apiRoutes = express.Router();

apiRoutes.post('/auth', function(req, res) {

   console.log(req.body)
});

app.use('/api', apiRoutes);
app.listen(port);

but at express when log the req.body i get this object { '{"name":"Nick","password":"password"}': '' } the whole json object is taken as a property having an empty value i don't understand or see what am doing wrong.

Upvotes: 1

Views: 73

Answers (2)

lin
lin

Reputation: 18392

Send Content-Type: application/json if you try to send an object. application/x-www-form-urlencoded expects an urlEncoded string as body property. The following both solutions should work for you, choose one.

Send JSON object as body with application/json content-type

$http({
    method  : 'POST',
    url     : 'http://localhost:8000/api/auth',
    data    : {
        name: user,
        password: passwd
    },
    headers : {'Content-Type': 'application/json'}
})
.success(function(data, status, headers, config){
    $scope.loginStatus=data;
})
.error(function(data, status, headers, config){
    $scope.lloginStatusogin=data;
});

 


Send urlEncoded sring in body with application/x-www-form-urlencoded content-type.

transformRequest will create a urlEncoded string based on data before the request will be send.

$http({
    method: 'POST',
    url: 'http://localhost:8000/api/auth',    
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
    },
    data: {
        name: user,
        password: passwd
    },
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status, headers, config){
    $scope.loginStatus=data;
})
.error(function(data, status, headers, config){
    $scope.lloginStatusogin=data;
});

Upvotes: 1

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

In the header part : it should be

{'Content-Type': 'application/json'} 

instead of

{'Content-Type': 'application/x-www-form-urlencoded'}

Upvotes: 1

Related Questions