angularjs $ http拦截器将覆盖其他http头

时间:2015-07-20 01:51:40

标签: angularjs http interceptor

我正在使用$ http拦截器配置我的http标头。

app.factory('httpRequestInterceptor', ['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {
var _request = function (config) {
    config.headers = config.header || {};
    var authData = localStorageService.get('authData');
    if (authData) {
        config.headers.Authorization = 'Bearer ' + authData.token;
    }
    return config;
}
var _responseError = function (rejection) {
    if (rejection.status == 401) {
        $location.path('/login');
    }
    return $q.reject(rejection);
}
return {
    request: _request,
    responseError: _responseError
}
}]);

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequestInterceptor');
}]);

不使用$ http拦截器(这意味着我发表评论

$httpProvider.interceptors.push('httpRequestInterceptor')

),我的帖子方法很好。

$http.post(RoutePrefix + "api/accounts/create", dataToSend, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    }).success(function (data, status, headers, config) {
        console.log("succes!");
    }).error(function (data, status, headers, config) {
        console.log("Error!");
    });

但是如果我使用$ http拦截器, 我将得到415(不支持的媒体错误)。

message: "The request entity's media type 'text/plain' is not supported for this resource."
exceptionMessage: "No MediaTypeFormatter is available to read an object of type 'CreateUserViewModel' from content with media type 'text/plain'."
exceptionType: "System.Net.Http.UnsupportedMediaTypeException"

关于我的问题的任何解决方案或建议?提前谢谢。

1 个答案:

答案 0 :(得分:0)

在线:

config.headers = config.header || {}

正确的部分在s字后缺少结束header字符。因此,config.headers初始化为{},因为config.headerundefined

但是,即使它是config.headers = config.headers || {},我认为它根本没有必要,也没有任何意义。