【问题标题】:$http post call hangs$http post 调用挂起
【发布时间】:2014-07-14 17:50:46
【问题描述】:

我正在尝试创建一个页面来显示所有论坛帖子...一切正常,但我注意到在我创建帖子后(当它重定向以显示所有帖子时) - 在 firebug 中,帖子调用挂了很长时间。但是,数据会通过发送,即使看起来帖子调用仍在等待中......因为它显示在包含所有帖子的页面上,然后立即加载。这就是我现在的做法。

后控制器(post.js):

'use strict';

angular.module('appApp')
.controller('PostCtrl', function ($location, $scope, $http) {
  $scope.errors = {};
  $scope.post;

  $scope.postit = function(form) {
    $scope.submitted = true;

    if(form.$valid) {
        console.log($scope.post.posttitle + " this is $scope.post");
        $http.post('/api/post', $scope.post).success(function() {console.log("no errors whoohoo")});
        $location.path('/forum');
    }
  };
});

如您所见,现在,我正在 post call 行之后执行重定向 ($location.path)。重定向可以像这样正常工作......但是 - 如果我尝试将重定向放在 success 函数中:

$http.post('/api/post', $scope.post).success(function() {$location.path('/forum'); console.log("no errors whoohoo")});

重定向永远不会发生,它只是挂在 post call 上。有谁知道发生了什么?我认为 post call 应该只需要几毫秒即可完成(它只是存储一个帖子标题和内容)。

无论我采用哪种方式,post 调用都会挂起...只是第二种方式不会重定向页面。

更新

正如 cmets 中所建议的,我的服务器端代码有问题 - 我可能已经隔离了问题。

这是当我想列出页面上的所有帖子时调用的函数(api.js):

exports.posts = function(req, res) {
  return Post.find(function (err, posts) {
    if (!err) {
      console.log(posts + " server side posts function route");
      return res.json(posts);
    } else {
      return res.send(err);
    }
  });
};

console.log 消息永远不会出现,所以这一定是它被挂断的地方......有什么想法吗?

调用此函数的代码区域如下所示:

app.route('/api/post')
    .get(api.posts);

这是我的特快路线之一。

【问题讨论】:

  • 您是否尝试过使用.then 而不是.success?在上面的示例中,它是否记录“没有错误哇”
  • @JaredReeves 刚刚尝试过 - 仍然挂起。
  • @JaredReeves - 消息也不会被记录...
  • 如果它没有进入成功回调,则意味着 $http 可能失败。你确定 api 正在返回任何东西吗
  • 你也试过放http错误处理程序吗?

标签: javascript angularjs redirect post


【解决方案1】:

事实证明,使用 $location.path('/xxx') 是不够的,我还需要在 express 端使用 res.redirect 才能使重定向真正起作用。 (必须同时使用)。

【讨论】:

    猜你喜欢
    • 2011-05-20
    • 1970-01-01
    • 2018-01-13
    • 2012-01-17
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多