2016-11-25 34 views
6

我從我的應用程序中獲取來自第三方REST服務的結果。這些服務因 Request header field X-XSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.而停止,因爲angular2已將此標頭設置爲默認情況下所有請求的標準。Angular 2爲單個服務或每個請求禁用XSRFStrategy

我已經想通了如何禁用此:

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 { } 

但這部作品在模塊級,這意味着無論哪個服務爲他們提供了它禁用此爲所有請求。

我想要的是爲我自己決定哪個Http調用應該被剝離這樣的頭文件並且可以繼續使用它們。使用上面的解決方案,我必須在單獨的模塊中隔離該服務,並且僅對該模塊使用NoXSRFStrategy。我沒有在其他模塊中與其他服務一起測試過,但我希望這不會將NoXSRFStrategy設置爲全局請求配置。

只是爲了說明,我想什麼是可能的:

@Injectable() 
export class MyService { 

    constructor(private http: Http) { } 
    apiCall() { 
    return this.http.get('some.online/service.json', {useXsrf: false}); // ...or something... IDK 
    } 

也許服務水平:

@Injectable() 
export class MyService { 

    constructor(private http: Http) { 
    this.http.setXsrfStrategy(NoXSRFStrategy); // For only this http instance... 
    } 

有誰知道是否有禁用X-XSRF-的任何方式TOKEN標題除了設置模塊級別配置?

+0

在這裏有相同的問題。你能解決它嗎? – Sebastian

+0

我不想爲我的整個應用程序在全局範圍內設置它,並最終放置了一個小型NodeJS Express服務器來處理我的角應用程序和第三方服務器之間的對話。但是如果你不關心爲你的應用程序所做的所有請求移除X-XSRF-TOKEN,上面的第一個代碼塊將爲你解決問題。 –

回答

1

我想通了!

你可以用你自己的方法覆蓋默認的Http類。這是我得到的最接近的Http攔截:

app.module.ts

@NgModule({ 
    declarations: [AppComponent], 
    imports: [HttpModule], 
    providers: [{ provide: Http, useClass: AuthHttp }], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 

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); 
     }); 
    } 
} 
-1

我就可以不再用它發送令牌。

document.cookie = "XSRF-TOKEN=; path=/" // <- add this 
this.http.get(url, options) 

只需清除名爲「XSRF-TOKEN」的cookie即可。

而且我做了一個擴展的Http類,可以選擇發送令牌或不發送。