Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

Response for preflight does not have HTTP ok status in angular

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.

question from:https://stackoverflow.com/questions/52047548/response-for-preflight-does-not-have-http-ok-status-in-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...