我有一个 Angular 前端,它需要登录表单的 ID 和密码,然后我将此值 POST 到 Node.js 服务器,并从该服务器将 JSON 对象发送回 Angular。
除了从 Angular 读取该对象之外,一切正常。我认为我已经完成了正确的步骤,但控制台显示“未定义”,就好像它无法识别该格式一样。
我是 Node 新手,这只是 try catch 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);
});
};
});
运行此程序时,控制台显示服务器响应未定义
。
预先感谢您的帮助。
最佳答案
根据Angular $http
documentation :
The response object has these properties:
- data – {string|Object} – The response body transformed with the transform functions.
- status – {number} – HTTP status code of the response.
- headers – {function([headerName])} – Header getter function.
- config – {Object} – The configuration object that was used to generate the request.
- statusText – {string} – HTTP status text of the response.
所以,如果您尝试response.data.ack
,那么它可能会起作用。
关于javascript - 如何从 Angular 读取 Node 服务器的json响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486341/