angularjs将请求发送到nodejs api

时间:2016-02-03 22:06:21

标签: angularjs node.js

我已将angularjs post call(提交登录表单数据)发送到/ login nodejs API端点。在Nodejs端点(在request.body中)收到的数据不是json格式,但它有额外的填充,如下所示, {'{“email”:“a @ b.com”,“密码”:“aaa”}':''} 这种格式是什么?如何从此对象访问“电子邮件”和/或密码?

客户端代码,

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) {
    });
}

服务器代码:

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

我错过了什么?任何帮助表示赞赏。

- Atarangp

1 个答案:

答案 0 :(得分:3)

默认情况下,angularjs使用JSON.stringify。如果你想使用x-www-form-urlencoded,你必须指定你的转换函数。

// 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
  });
相关问题