Response for preflight does not have HTTP ok status in angular

  • A+
Category:Languages

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.

 


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 response is not a 2xx, or the header is not present, or the header does 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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: