angular-js:为已取消的请求设置HTTP状态代码 [英] angular-js: Set HTTP status code for cancelled requests

查看:200
本文介绍了angular-js:为已取消的请求设置HTTP状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取消这样的http请求时:

When cancelling an http request like this:

$scope.runTest = function() {
    if (canceler) canceler.resolve();
    canceler = $q.defer();
    $http({
        method: 'GET',
        url: 'http://www.google.com/',
        timeout: canceler.promise
    })
    .success(function(data) {
        $scope.result.push({msg: "this won't be displayed on cancel"});
    })
    .error(function(data) {
        $scope.result.push({msg: "this will be displayed on cancel"});
    });
};

是否可以使取消的HTTP请求具有特定的HTTP代码,如205?它会导致http拦截器被http状态0触发,这也用于超时或没有网络连接。我希望能够区分拦截器中的两个场景

Is it possible to make the cancelled HTTP request have a specific HTTP code, like 205? It causes http interceptors to be triggered with http status 0, which is also used for timeouts or no network connection. I'd like to be able to differentiate between the two scenarios in the interceptors

谢谢!

推荐答案

我最终采用了以下方法:

I ended up with the following approach:

$scope.runTest = function() {

    if (canceler) {
        // Set non-zero status for http interceptors
        // Using 499, an nginx extension to flag cancelled http requests
        // Could be something else like a boolean, using status code for convenience
        canceler.promise.status = 499;

        // Cancel the request
        canceler.resolve();
    }

    canceler = $q.defer();
    $http({
        method: 'GET',
        url: 'http://www.google.com/',
        timeout: canceler.promise
    })
    .success(function(data) {
        // On sucesss
    })
    .error(function(data) {
        // On error
    });
};

这里我只是在超时时设置了一些内容,将请求标记为已取消,正如@Daniel Silva建议的那样。然后在我的http拦截器上:

Here I just set something on the timeout to flag the request as cancelled, as @Daniel Silva suggested. Then on my http interceptor:

app.config(function($httpProvider) {

    $httpProvider.interceptors.push(function($q) {
        return {
            'responseError': function(response) {

                var statusCode = response.status;

                // Get status from timeout, if 0 and timeout present
                if (statusCode === 0 && response.config.timeout) {
                    statusCode = response.config.timeout.status;
                }

                // Ignore client request cancelled
                if (statusCode === 499) {
                    return response;
                }

                // Reject via $q, otherwise the error will pass as success
                return $q.reject(response);
            }
        };
    });
});

这篇关于angular-js:为已取消的请求设置HTTP状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆