1

I've angularjs post call (submit a login form data) to a /login nodejs API endpoint. The data received at Nodejs endpoint (in request.body) is not in json format but it has extra padding as shown below, { '{"email": "[email protected]", "password": "aaa"}': ''} What is this format? How do I access 'email' and/or password from this object?

Client code,

login: function(loginData, callback) {
  $http({
    method: 'POST',
    url: '/api/login',
    data: loginData,
    headers: {'Content-Type': 'application/x-www.form-urlencoded'}
  }).then(function successCallback(response) {
    }, function errorCallback(response) {
    });
}

Server code:

app.post('/login', function(req, res) {
  console.log('Email:' + req.body.email);  //this gives undefined error
  console.log(req.body);   // shows { '{"email": "[email protected]", "password": "aaa"}': ''}
}

What am I missing? Any help is appreciated.

--Atarangp

2
  • You have a stringified object in your body - JSON.parse(req.body) Commented Feb 3, 2016 at 22:08
  • JSON.parse() gives internal server error with 'Unexpected token o' error in Object.parse Commented Feb 3, 2016 at 22:25

1 Answer 1

3

By default angularjs use JSON.stringify. If you wanna use x-www-form-urlencoded, you have to specify your transform function.

// transforme obj = {attr1: val1} to "attr1=" + encodeURIComponent(val1) + "&attr2=" ... 
function transformRequestToUrlEncoded(obj) {
    var str = [];
    for(var p in obj)
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
  }

$http({
    method: 'POST',
    url: your_url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
    transformRequest: transformRequestToUrlEncoded, // specify the transforme function
    data: datas
  });
Sign up to request clarification or add additional context in comments.

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.