2015-07-20 91 views
0

我使用$ 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" 

有關我的問題的任何解決方案或建議?提前致謝。

+0

你確定它在'config.headers = config.header ||中是真的'config.header'嗎? {}'?它似乎刪除了請求中的所有現有標題。 – limekin

+0

是的,我認爲這應該沒問題。因爲當我調用post方法時,我手動添加頭的內容類型。 – user3461311

+0

我不認爲攔截器是這樣工作的。它實際上攔截了你所做的請求,我的意思是你使用頭進行請求,並在它被髮送到服務器之前被請求攔截器攔截,並清除頭。 – limekin

回答

0

就行了:

config.headers = config.header || {} 

右邊是後header字失蹤結束s字符。因此config.headers被初始化爲{},因爲config.headerundefined

但是,即使它被寫入config.headers = config.headers || {},我認爲它根本沒有必要,也沒有任何意義。