I have an angular application, and as soon as I add the service to the service, follow these steps:
https://github.com/angular/angular-cli/blob/master/docs/documentation/build.md#service-worker https://angular.io/guide/service-worker-getting-started
... my API requests no longer have an Origin request header, which seems to cause my API server not to return an Access-Control-Allow-Origin response header, causing a browser error:
No header "Access-Control-Allow-Origin" is present on the requested resource.
Just deleting the Worker service and unregistering returns normal behavior.
How can I implement serviceWorker while continuing to use my restful API?
All requests are affected, but some of them are made "under the hood" on oidc-client ; everyone else looks like this:
public getBook(bookId: number): Observable<Book> { const request = new HttpRequest( 'get', `https://some-server.asurewebsites.net/api/book/${bookId}`, { reportProgress: true, responseType: 'json' } ); return this.httpClient.request<any>(request).do(event => { this.progressService.processEvent(event); }).filter(event => event instanceof HttpResponse) .map((response: HttpResponse<any>) => deserializeBook(response.body)).catch(error => { if (error instanceof HttpErrorResponse) { if (error.status === 404) { return Observable.of(null); } } return Observable.throw(error); }); }
Update1:
Entering manually Origin I get:
Denied to set insecure Origin header
Manually setting Access-Control-Allow-Origin does nothing, because this is the response header.
The Fetch API has Request.mode , which when set to 'cors' will send an OPTIONS request with an Origin header, as usual. I would try to explicitly install this, but I am having trouble finding or finding in the documentation how to install this using angular HttpClient
Update2:
I tried converting one of the requests to use the Fetch API. So I set Request.mode to 'cors' , but I still don't get the Origin request header and Access-Control-Allow-Origin response header.
public getBookList(): Observable<BookList[]> { const fetchHeaders = new Headers(); fetchHeaders.set('Authorization', 'Bearer ${token}'); const fetchRequest = new Request(`https://some-server.asurewebsites.net/api/book`, { method: 'get', headers: fetchHeaders, mode: 'cors' }); return Observable.fromPromise(fetch(fetchRequest).then(response => response.json())) .map((results: any[]) => results.map(entity => deserializeBook(entity))); }

TL; DR
After registering a service worker, the browser no longer uses CORS, even if mode: 'cors' explicitly set by the client. How to use a service worker and CORS?