我有一个Angular前端,它为登录表单获取id和密码,然后我将此值发送到node.js服务器,并从此服务器将JSON对象发送回Angular。
除了从Angular读取此对象外,一切正常。我想我已经做了正确的步骤,但是控制台告诉我" undefined"好像它不能识别格式。
我是节点的新手,这只是一个尝试从节点捕获响应的示例。
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/');
});
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
。
提前感谢您的帮助。
答案 0 :(得分:3)
根据Angular $http
documentation:
响应对象具有以下属性:
- 数据 - {string | Object} - 使用转换函数转换的响应正文。
- 状态 - {number} - 响应的HTTP状态代码。
- 标题 - {function([headerName])} - 标头获取功能。
- config - {Object} - 用于生成请求的配置对象。
- statusText - {string} - 响应的HTTP状态文本。
因此,如果您尝试response.data.ack
,那么它可能会有用。
答案 1 :(得分:1)
尝试
console.log("Server response "+ response.data);
而不是
console.log("Server response "+response.ack);