【发布时间】:2016-05-30 21:45:47
【问题描述】:
我有一个 Angular 前端,它获取登录表单的 id 和密码,然后我将此值发布到 node.js 服务器,并从该服务器将 JSON 对象发送回 Angular。
除了从 Angular 读取此对象外,一切正常。我认为我已经完成了正确的步骤,但控制台向我显示“未定义”,就好像它无法识别格式一样。
我是 node 新手,这只是尝试从 node 捕获响应的示例。
我的服务器端 JS(Node.js):
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.post('/login',function(req,res){
console.log("sono nella post "+req.body.username);
res.setHeader('Content-Type', 'application/json');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
res.json({ack:'ok'});
});
app.listen(9080,function(){
console.log('Server running at http://127.0.0.1:9080/');
});
我的客户端 JS(Angular):
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope,$http){
$scope.check = function(data) {
var id = data.form.id;
var pwd = data.form.password;
console.log("utente è "+id+",password è "+pwd);
var msg = {username: id,password: pwd};
$http({
// without anything here, put * in app.post()
url : 'http://localhost:9080/login',
method : "POST",
data : $.param(msg),
responseType : "application/json",
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
console.log("Server response "+response.ack);
});
};
});
运行时,控制台显示Server response undefined。
提前感谢您的帮助。
【问题讨论】:
-
第一步应该是以下之一:在回调中添加调试器行并检查
response的值,添加断点并执行相同操作,或直接使用console.log(response) .这可能会为您解决问题,而您不必花时间和我们的时间在这里。 -
console.log 只会让你到目前为止。打开 chrome 开发工具,在遇到问题的代码处设置断点并检查对象。编辑:如果您打算使用 console.log 然后 console.log(JSON.stringify(response));会给你更丰富的反馈。
-
感谢您的回答,我已经使用 response.data.ack 解决了。非常感谢!
标签: javascript angularjs json node.js