我从我的应用程序中的第三方REST服务获取结果.这些服务Request header field X-XSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.失败,
因为angular2已将此标头设置为默认情况下所有请求的标准.
我已经想出如何禁用它:
import { HttpModule, XSRFStrategy } from '@angular/http';
export class NoXSRFStrategy {
configureRequest(req: Request) {
// Remove `x-xsrf-token` from request headers
}
}
@NgModule({
imports: [
HttpModule
],
declarations: [ ],
providers: [{ provide: XSRFStrategy, useFactory: () => new NoXSRFStrategy() }] // !!HACK!!
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
但这适用于模块级别,这意味着它会对所有请求禁用此功能,无论哪个服务提供它们.
我想要的是,为自己决定哪个Http调用应该被剥夺这样的标题,哪些可以继续使用它们.通过上面的解决方案,我必须在单独的模块中隔离服务,并NoXSRFStrategy仅使用for this模块.我没有在其他模块中与其他服务一起测试这个,但我希望这不会设置NoXSRFStrategy为全局请求配置.
只是为了说明我希望能做到的事情:
@Injectable()
export class MyService {
constructor(private http: Http) { }
apiCall() {
return this.http.get('some.online/service.json', {useXsrf: false}); // ...or something... IDK
}
Run Code Online (Sandbox Code Playgroud)
或者也许在服务级别:
@Injectable()
export class MyService {
constructor(private http: Http) {
this.http.setXsrfStrategy(NoXSRFStrategy); // For only this http instance...
}
Run Code Online (Sandbox Code Playgroud)
除了设置模块级别配置之外,有没有人知道是否有任何方法可以禁用X-XSRF-TOKEN标头?
我想到了!
您可以用自己的类覆盖默认的 Http 类。这是我最接近的 Http 拦截器:
应用程序模块.ts
@NgModule({
declarations: [AppComponent],
imports: [HttpModule],
providers: [{ provide: Http, useClass: AuthHttp }],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
AuthHttp.ts
import {Injectable} from '@angular/core';
import {Http, Request, Response, RequestOptionsArgs, RequestOptions, XHRBackend} from '@angular/http';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
@Injectable()
export class AuthHttp extends Http {
constructor(backend: XHRBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
// Setup default http headers here
defaultOptions.headers.append('Cache-control', 'no-cache');
defaultOptions.headers.append('Cache-control', 'no-store');
defaultOptions.headers.append('Pragma', 'no-cache');
defaultOptions.headers.append('Expires', '0');
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
// Before request execution. You can manipulate headers per request here.
return super.request(url, options)
.map(res => { // Successful Response
return res;
})
.catch((err: any) => { // Unsuccessful Response.
return Observable.throw(err);
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1300 次 |
| 最近记录: |