我在与此相同的结构中有很多请求:
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:左侧无效分配
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 :(得分:3)
您不能在变量名中使用-
。
尝试:
config.headers["Content-Type"] = 'application/x-www-form-urlencoded';