我必须向运行localhost:3001的节点服务器发送一个post请求。我成功地完成了请求,并在节点服务器中获得了帖子数据,但数据格式不好。
AngularJS:
function MyCtrl1($scope,$http,$location) {
$scope.user = { };
$scope.login = function() {
$http.post("http://localhost:3001/login",
$scope.user,
{'Content-Type': 'application/json'}).success(function(result) {
$scope.resultPost = result;
$location.path('/');
}).error(function() {
console.log("error");
});
};
}
Nodejs:
app.post('/login', function(req,res) {
console.log(JSON.stringify(req.body));
res.end('ok');
});
log : {"{"username":"test","password":"pass123"}":""}
有什么方法可以在这里获得格式化的数据吗?
您可以使用JSON.parse()将主体解析为JavaScript对象。
var obj = JSON.parse(req.body);
var username = obj.username;
var password = obj.password;