我有很多请求与这个结构相同:
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 header 时,如下所示:
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 文档,但在那里没有找到答案。
最佳答案
您不能在变量名中使用-
。
尝试:
config.headers["Content-Type"] = 'application/x-www-form-urlencoded';
关于angularjs - 无法将 Content-Type header 放入拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34118635/