【问题标题】:Return error to Angular from Express从 Express 向 Angular 返回错误
【发布时间】:2017-01-02 05:16:47
【问题描述】:

我有一个应用程序,用户可以在其中将电影添加到他们的观看列表中。我想阻止用户添加他们的观看列表中已经存在的电影。

这是我的 Angular 控制器中的 addMovie 函数:

$scope.addMovie = function (movie)  {
    movieFactory.selectMovie(movie).then(function(response){
        movieFactory.addMovie(response);
        Notification.success(movie.title + ' has been added to your watchlist');
        $scope.movies = [];
        $scope.overlay = false;
        $scope.searchquery = '';
        $rootScope.$broadcast('onAddMovieEvent', response);
    });
};

我通过最初的 ng-click 传递了电影对象。然后我在movieFactory 中请求一个selectMvoie 函数,该函数从TMDB api 获取正确的电影数据。

然后我调用movieFactory 工厂中的addMovie 函数,并使用来自selectMovie 函数的响应。

factory.addMovie = function (movie) {
    var deferred = $q.defer();
    $http({
        method: 'POST',
        url: '/movies',
        data: movie
    })
        .success(function (data) {
            deferred.resolve(data);
        })
        .catch(function () {
            deferred.reject();
        });
    return deferred.promise;
};

这是一个 /post 请求,该请求进入我的 Express 路由:

router.post('/', function(req,res){
    pool.getConnection(function(err, connection) {

        connection.query('SELECT * FROM user_movieid WHERE movie_id= ? AND userid= ?' ,[req.body.id, req.user.id] , function(err, result) {
            for (var i = result.length - 1; i >= 0; i--) {

                if (movie.id === result[i].movie_id) {
                    console.log('exists');
                }
            }
        });
    });
})

还有一个 connection.query 将电影发布到数据库中,但现在不相关了。

我现在的情况是,当我发布已经存在的电影时,我的节点控制台会显示消息 exists,但仍会发布电影(显然)。

如何将“错误”状态返回到 Angular 控制器中的 addMovie 函数,以便我可以执行 if 语句来显示不同的通知?

【问题讨论】:

    标签: angularjs node.js express


    【解决方案1】:

    如果您想让您的 API 保持“安静”,那么我将返回带有非 2xx 状态代码的响应。我认为 409 Conflict 适合这种情况。

    router.post('/', function(req,res){
        pool.getConnection(function(err, connection) {
    
            connection.query('SELECT * FROM user_movieid WHERE movie_id= ? AND userid= ?' ,[req.body.id, req.user.id] , function(err, result) {
                for (var i = result.length - 1; i >= 0; i--) {
    
                    if (movie.id === result[i].movie_id) {
                        console.log('exists');
                        // choose an appropriate status code, probably a conflict 409 in this case
                        return res.status(409).send('Movie already exists in your watchlist')
                    }
                }
            });
        });
    })
    

    然后在您的 Angular 代码中,您可以通知用户该电影已经在他们的列表中。

    $scope.addMovie = function (movie)  {
        movieFactory.selectMovie(movie).then(function(response){
            movieFactory.addMovie(response);
            Notification.success(movie.title + ' has been added to your watchlist');
            $scope.movies = [];
            $scope.overlay = false;
            $scope.searchquery = '';
            $rootScope.$broadcast('onAddMovieEvent', response);
        })
        // catch any errors
        .catch(function() {
          // ideally you should check the status code here and probably handle other non 409 status codes differently
          // since this .catch will execute for any other 4xx and 5xx errors
          Notification.fail(movie.title + ' is already in your watchlist');
        });
    };
    

    【讨论】:

    • 谢谢,我不得不稍微更改一下代码,以使 .catch 符合正确的工厂请求,但它现在可以工作了。
    猜你喜欢
    • 2021-12-24
    • 2014-01-14
    • 2016-04-13
    • 1970-01-01
    • 2022-08-05
    • 2018-07-01
    • 2015-04-08
    • 1970-01-01
    • 2019-12-03
    相关资源
    最近更新 更多