我试试这样从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对象被视为具有空值的属性,我不明白或看错了什么。
答案 0 :(得分:1)
在标题部分:它应该是
{'Content-Type': 'application/json'}
而不是
{'Content-Type': 'application/x-www-form-urlencoded'}
答案 1 :(得分:1)
如果您尝试发送对象,请发送Content-Type: application/json
。 application/x-www-form-urlencoded
期望urlEncoded字符串作为body属性。以下两种解决方案都适合您,请选择一种。
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;
});
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;
});