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

我想这样发送一些JSON数据从angularjsexpression/ 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); 

但在loginreq.bodyexpression时,我得到这个对象{ '{"name":"Nick","password":"password"}': '' }整个JSON对象被视为一个具有空值我不明白或看到做错了什么。

如果您尝试发送对象,请发送Content-Type: application/jsonapplication/x-www-form-urlencoded需要一个urlEncodedstring作为body属性。 以下两个解决scheme应该为你工作,select一个。

使用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 content-type发送urlEncoded sring。

在请求发送之前, transformRequest将根据data创build一个urlEncodedstring。

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

在标题部分:应该是

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

代替

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