Angular 4 - setting withCredentials on every request - cors cookie
You can use an HttpInterceptor
.
@Injectable()export class CustomInterceptor implements HttpInterceptor { constructor() { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { request = request.clone({ withCredentials: true }); return next.handle(request); }}
Next you have to provide it:
@NgModule({ bootstrap: [AppComponent], imports: [...], providers: [ { provide: HTTP_INTERCEPTORS, useClass: CustomInterceptor , multi: true } ]})export class AppModule {}
Another perhaps more simple way is to create your own ApiService. It would use an injected HttpClient
. All XHR requests would use the ApiService instead of HttpClient directly.
Here is an example implementation:
Some of the code that I have modified:
@Injectable()export class ApiService { private httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), withCredentials: true // to allow cookies to go from "https://localhost:4567" to "http://localhost:5678" }; constructor( private http: HttpClient ) { } private formatErrors(error: any) { return throwError(error.error); } get(path: string, params: HttpParams = new HttpParams()): Observable<any> { return this.http.get(`${environment.api_url}${path}`, { params }) .pipe(catchError(this.formatErrors)); } put(path: string, body: Object = {}): Observable<any> { return this.http.put( `${environment.api_url}${path}`, JSON.stringify(body), this.httpOptions ).pipe(catchError(this.formatErrors)); } post(path: string, body: Object = {}): Observable<any> { return this.http.post( `${environment.api_url}${path}`, JSON.stringify(body), this.httpOptions ).pipe(catchError(this.formatErrors)); }