有人见过这个吗?
如果我的 Angular Controller $http post 中没有包含数据参数,那么 Express 侧路由将被拾取并运行,但如果我添加数据元素,它会挂起并且不会拾取路由 - 最终 Chrome 调试器会显示错误:net::ERR_EMPTY_RESPONSE。
这有效:
$scope.newAccount = function(){
console.log("Got a submit request for new account: " );
$http.post("http://localhost:3000/newAccount").success(function( data, status, headers, config ){
console.log("SUCCESS on NEW ACCOUNT");
$scope.mode = data;
}).error(function(data, status, headers, config) {
console.log("Got ERROR");
});};
这不起作用:
$scope.newAccount = function(){
console.log("Got a submit request for new account: " );
$http.post("http://localhost:3000/newAccount",{info:"toSend"}).success(function( data, status, headers, config ){
console.log("SUCCESS on NEW ACCOUNT");
$scope.mode = data;
}).error(function(data, status, headers, config) {
console.log("Got ERROR");
});
};
这是不会改变的 Express 处理程序(实际逻辑被删除):
app.post('/newAccount', function (req, res) {
console.log("GOT A POST REQUEST: " );
....some code here
res.setHeader("Access-Control-Allow-Origin", "*");
res.send( "successful post" );
});
最佳答案
所以,这个问题与远程访问授权有关。 Chrome 调试器提供了一些相当蹩脚的信息。 Firefox 调试器更加清晰。之前我设置了 res.header("Access-Control-Allow-Origin", "*");在发送响应之前直接在路由处理程序中。这解决了没有数据元素的原始调用的相同问题。但是,为了使其能够与数据元素一起使用,必须将以下内容添加到我的 Express 应用程序中 - 而不是在路由处理程序本身中进行设置。当然是更好的编程实践,但我只是想了解一些东西来了解 Node/Express。在这件事上浪费了很多时间。
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
关于angularjs - Angular $http 发布到 Express 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28490951/