1

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.

5
  • 1
    Try to change the header 'Content-Type': 'application/x-www-form-urlencoded' to 'Content-Type: application/json' Commented Mar 29, 2017 at 12:39
  • Any feedback or suggestions Xsmael? Commented Mar 29, 2017 at 13:16
  • @Dario ir didnt mention it, but i tried that also and it didn't work Commented Mar 29, 2017 at 15:30
  • @lin Sorry i was offline... Commented Mar 29, 2017 at 15:30
  • No problem m8 =) Commented Mar 29, 2017 at 15:31

2 Answers 2

1

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;
});
Sign up to request clarification or add additional context in comments.

5 Comments

does $.param use jQuery ?
Oww yea, shit hold on I add the correct way for angularjs by transform the data.
how did you know about the transformRequest ? i never saw that, cool dude!
Well made, x-www-form-urlencoded is some web standard long before AngularJS was created. In that way its pretty easy to know what kind of body is expected on that request. =) I was facing this "problem" years ago in AngularJS. Glad to help
Yea, experience matters, thanks i wasted 1 one whole day on this isssue :( ( but it could have been worse :) )
1

In the header part : it should be

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

instead of

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.