I'm trying to add basic authentification to my angular2 app.
public login() { // Set basic auth headers this.defaultHeaders.set('Authorization', 'Basic ' + btoa(this.username + ':' + this.password)); console.log('username', this.username) console.log('password', this.password) console.log(this.defaultHeaders) // rest is copy paste from monbanquetapiservice const path = this.basePath + '/api/v1/development/order'; let req = this.http.get(path, { headers: this.defaultHeaders }); req.subscribe( _ => { }, err => this.onError(err) ); }
What I expect to see is a GET request with the Authorization
header I put.
But what I see is first a OPTIONS with this headers:
OPTIONS /api/v1/development/order HTTP/1.1 Host: localhost:8080 Connection: keep-alive Access-Control-Request-Method: GET Origin: http://localhost:3000 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36 Access-Control-Request-Headers: authorization, content-type Accept: */* Referer: http://localhost:3000/ Accept-Encoding: gzip, deflate, sdch Accept-Language: en-GB,en-US;q=0.8,en;q=0.6,fr;q=0.4
Since my server doesn't allow OPTIONS on this url, I get an error.
I know that some methods like PUT or POST send first an OPTIONS method to preflight the request, but GET doesn't.
Why does angular2's http send a OPTIONS first?
Thanks.
This is the way CORS works (when using cross domain requests). With CORS, the remote Web application (here the one with domain mydomain.org) chooses if the request can be served thanks to a set of specific headers.
The CORS specification distinguishes two distinct use cases:
It's not Angular2 that sends the OPTIONS request but the browser itself. It's not something related to Angular.
For more details, you could have a look at this article:
Why am I getting an OPTIONS request instead of a GET request?
That is a CORS preflight request that is generated by the browser itself.
See also
- How to disable OPTIONS request?
The server needs to be configured to support CORS requests, only then the actual GET
request is sent by the browser after the OPTIONS
request.
See also
- "No 'Access-Control-Allow-Origin' header is present on the requested resource" - https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Access-Control-Allow-Credentials
Indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple GET requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With