【问题标题】:Angular $http post to Express hangsExpress 的 Angular $http 帖子挂起
【发布时间】:2015-04-13 23:37:38
【问题描述】:

有人见过这个吗?

如果我没有在我的角度控制器 $http 帖子中包含数据参数,那么快速侧路由会被拾取并运行,但如果我添加一个数据元素,它会挂起并且不会拾取路由 - 最终 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" );
    });

【问题讨论】:

  • 你在使用bodyParser吗?
  • 是的,使用 :var bodyParser = require('body-parser'); app.use(bodyParser.json());
  • 首先要做的是确保您没有任何其他可能影响它的中间件。也许放置某种空白中间件(可能在 bodyparser 之后),它只是 console.log 的请求,然后调用 next()。

标签: angularjs node.js express


【解决方案1】:

所以,事实证明这个问题与远程访问授权有关。 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();
    });

【讨论】: