I have the following get request defined in my service:
createAuthorizationHeader(user, pass) { let headers: HttpHeaders = new HttpHeaders; headers = headers.append('Accept', 'application/json, text/plain, */*'); headers = headers.append('Authorization', 'Basic ' + btoa(user + ':' + pass)); headers = headers.append('Content-Type', 'application/json; charset=utf-8'); console.log(headers); return this.http.get(this._loginUrl, { headers: headers }); }
The result is:
OPTIONS https://localhost:8443/delivery/all 401 () Failed to load https://localhost:8443/delivery/all: Response for preflight does not have HTTP ok status. HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}
I also have made the same post request with Postman, but everything works, so the local server works.
I can't figure out what am I doing wrong with my request.
A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers. It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method , Access-Control-Request-Headers , and the Origin header.
A CORS preflight OPTIONS request can be triggered just by adding a Content-Type header to a request — if the value's anything except application/x-www-form-urlencoded , text/plain , or multipart/form-data .
A preflight request is a small request that is sent by the browser before the actual request. It contains information like which HTTP method is used, as well as if any custom HTTP headers are present. The preflight gives the server a chance to examine what the actual request will look like before it's made.
Preflight cache behaves similarly to any other caching mechanism. Whenever the browser makes a Preflight request, it first checks in the Preflight cache to see if there is a response to that request.
The CORS contract requires that authentication not be required on the pre-flight OPTIONS request. It looks like your back-end is requiring authentication on the OPTIONS request and the GET.
When you access your back-end with Postman, you are only sending a GET. The browser will send an OPTIONS request first (without your authentication header), and look for the response to have an "Access-Control-Allow-Origin" header that matches the origin of the page making the request.
If the response to the OPTIONS request is not a 2xx, or the header is not present, or the header value does not match the requesting page's origin, you will get the error that you are experiencing, and the GET request will not be made.
TLDR; change your back-end to not require authentication for the OPTIONS method when handling the login url.
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