2015-12-06 96 views
0

我有相同的結構很多請求,因爲這一個:不能把Content-Type頭在攔截

angular.module('factories') 
    .factory('encodedFormInterceptor', function($window, $q, $http) { 
    return { 
     request: function(config) { 
     config.headers = config.headers || {}; 
     config.headers.Content-Type = 'application/x-www-form-urlencoded'; 

     return config || $q.when(config); 
     }, 
     response: function(response) { 
     if (response.status === 401) { 

     } 
     return response || $q.when(response); 
     } 
    }; 
    }); 

但是,當我嘗試設置Content-Type頭在一個單獨的攔截器,這樣:

angular.module('factories') 
    .factory('encodedFormInterceptor', function($window, $q, $http) { 
    return { 
     request: function(config) { 
     config.headers = config.headers || {}; 
     config.headers.Content-Type = 'application/x-www-form-urlencoded'; 

     return config || $q.when(config); 
     }, 
     response: function(response) { 
     if (response.status === 401) { 

     } 
     return response || $q.when(response); 
     } 
    }; 
    }); 

我得到這個錯誤:

ReferenceError: invalid assignment left-hand side

config.headers.Content-Type = 'application/x-www-form-urlencoded';

我已在使用另一個攔截器進行授權,其工作

罰款:

angular.module('factories') 
    .factory('AuthInterceptor', function($window, $q) { 
    return { 
     request: function(config) { 
     config.headers = config.headers || {}; 
     if ($window.localStorage.getItem('eva-token')) { 
      config.headers.Authorization = 'Bearer ' + $window.localStorage.getItem('eva-token'); 
     } 
     return config || $q.when(config); 
     }, 
     response: function(response) { 
     if (response.status === 401) { 

     } 
     return response || $q.when(response); 
     } 
    }; 
    }); 

那麼我怎麼能把其他頭類型在攔截器?我檢查了AngularJS文檔,但沒有找到答案。

+0

連字符怎麼樣? 「config.headers.Content-Type」看起來像錯誤的語法。 –

回答

2

您不能在變量名中使用-。 Try:

config.headers["Content-Type"] = 'application/x-www-form-urlencoded';