2015-12-06 100 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';