在angularjs中,响应为304(未修改)时,$ http返回错误 [英] $http returns error when response is 304 (Not Modified) in angularjs

查看:71
本文介绍了在angularjs中,响应为304(未修改)时,$ http返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angularjs $ http向ASP Net Web API发出请求.服务器上的Web API通过ETag管理缓存.如果我的响应状态代码是304,则它进入错误功能而不是成功.我不明白angularjs这种怪异行为的原因是什么.下面是我的代码

I'm using angularjs $http for making request to asp net web api. The web api on the server manages the caching via ETags. If my response status code is 304 then it goes in the error function and not in the success. I don't understand what is the reason for this weird behavior of angularjs. Below is my code

function getEmployeesPartial(pageIndex, pageSize) {
        var deferred = $q.defer();
        var uri = config.remoteServiceName + 'odata/Employees?$select=EmployeeId,FirstName,LastName,Email,Designation/Name&$top=' + pageSize + '&$skip=' + (pageIndex * pageSize) + '&$inlinecount=allpages' + '&$expand=Designation';
        var authData = common.getAuthData();
        var authHeaderValue = "Bearer " + authData.token;
        var etagHeaderValue = angular.empty;
        if (common.etag !=angular.empty) {
            etagHeaderValue = common.etag;
        }
        $http.get(uri, { headers: { 'Authorization': authHeaderValue,'If-None-Match':etagHeaderValue } }).success(function (response, status, headers, httpconfig) {
            // alert(headers('Etag'));
            common.etag = headers('Etag');
           deferred.resolve(response);
        }).error(function (err, status, headers, httpconfig) {
            if (status === 500) {
                deferred.reject(err['odata.error'].innererror.message);
            }
            deferred.resolve();

        });

        return deferred.promise;
    }

有什么想法吗?

推荐答案

我们通过实现HTTP拦截器并让拦截器以状态304解析而不是拒绝来解决该问题.

We have solved the problem by implementing a HTTP interceptor and letting the interceptor resolve on status 304 rather than reject.

// register the interceptor as a service
$provide.factory('myHttpInterceptor', function ($q, dependency1, dependency2) {
    return {

        'responseError': function (rejection) {
            if (rejection.status === 304)  return $q.resolve(rejection);

            return $q.reject(rejection);
        }
    };
});

这篇关于在angularjs中,响应为304(未修改)时,$ http返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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