使用$ http将数据从angularJS发布到Express

时间:2017-03-29 12:35:15

标签: angularjs json node.js api express

我试试这样从angularjs发送一些json数据来表达/ nodejs

AngularJS代码:

$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代码:

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

但是在记录时req.body我得到这个对象 { '{"name":"Nick","password":"password"}': '' }时,整个json对象被视为具有空值的属性,我不明白或看错了什么。

2 个答案:

答案 0 :(得分:1)

在标题部分:它应该是

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

而不是

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

答案 1 :(得分:1)

如果您尝试发送对象,请发送Content-Type: application/jsonapplication/x-www-form-urlencoded期望urlEncoded字符串作为body属性。以下两种解决方案都适合您,请选择一种。

使用application/json content-type

将JSON对象作为正文发送
$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;
});

使用application/x-www-form-urlencoded内容类型在正文中发送urlEncoded sring。

transformRequest会在发送请求之前根据data创建一个urlEncoded字符串。

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