angular


Angular 2 disable XSRFStrategy for a single service or per request


I fetch results from third party REST services in my application. These services stall with
Request header field X-XSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response. because angular2 has set this header as a standard for all requests per default.
I've figured out how to disable this:
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 { }
But this works on a module level, meaning it disables this for all requests regardless of which service provides them.
What I would like, is to decide for my self which Http call that should be stripped of such headers and which can continue using them. With the solution above, I have to isolate the service in a separate module and use the NoXSRFStrategy for only this module. I haven't tested this in conjunction with other services in other modules, but I hope this does not set NoXSRFStrategy as a global request config.
Just to illustrate what I would like to be possible:
#Injectable()
export class MyService {
constructor(private http: Http) { }
apiCall() {
return this.http.get('some.online/service.json', {useXsrf: false}); // ...or something... IDK
}
Or perhaps on service level:
#Injectable()
export class MyService {
constructor(private http: Http) {
this.http.setXsrfStrategy(NoXSRFStrategy); // For only this http instance...
}
Does anybody know if there is any way of disabling the X-XSRF-TOKEN header other than setting a module level config?
I figured it out!
You can override the default Http class with your own. This is the closest I got to a Http Interceptor:
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);
});
}
}

Related Links

Selectors name when naming directives
How to Authenticate Angular 2 with Firebase API using Auth0
Include user_metadata and app_metadata in JWT using Auth0
Primeng component calendar have a method for close the pop up calendar manually?
Angular test does not include import from node_modules
Convert Angular 4 web app to Angular Universal app
Generate a routing module while creating a module in angular-cli
What is the best practice to manage sessions with Ionic 2
Angular 2 Updating Component After Form Submit With New Data From Response
How to configure and use Auth-0 in Angular4
How to get meta tags work correctly in angular 2? [closed]
Angular2-highcharts switching option
How to make ViewChild work in a unit test
Angular 2 AOT: Getting lot of errors in index.d.ts
Angular2 doesn't work Custom Reuse Strategy with Lazy module loading
view not updated while changing class variable value angular2

Categories

HOME
react-native
google-maps
processing
drawing
ruby-on-rails-4
angular-material2
statistics
userform
visual-foxpro
uinavigationcontroller
css-modules
rhel
zk
sourceforge
angularjs-ng-route
fix
jlabel
junit4
cognos-10
prestashop-1.6
spring-boot-actuator
bootstrap-select
cpu-registers
code-injection
fgets
google-developers-console
fork
jqxwidgets
revit
robotium-recorder
ctype
vowpalwabbit
ggiraph
nexmo
kinvey
sequences
fixtures
submenu
lightgallery
direct3d9
james
envelope
zlib
clisp
canvas-lms
sqlitestudio
equation-solving
live-connect-sdk
lab-color-space
jquery-events
banking
suppress-warnings
git-stash
metamodel
post-commit
dde
google-plus-domains
qtquick2
datepart
codeigniter-restserver
antivirus-integration
anthill
testdroid
nibble
google-roads-api
highcharts-ng
ionic-view
cts
distinct-on
busy-waiting
fody-propertychanged
avm2
html5builder
bpopup
certificatestore
ontouchevent
code-completion
ngen
irssi
jquery-dynatree
searchqueryset
usleep
tracker
cxf-client
jform-designer
bonjour
teamcity-7.1
pyro
rails-i18n
spn
ubuntu-13.04
problem-steps-recorder
agi
sniffing
outlook-2003
jwebunit
scalaquery
mono-service
cgpoint
cloning
dft
loose-coupling
uint32
zero-pad

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App