预检响应在角度中没有 HTTP ok 状态 [英] Response for preflight does not have HTTP ok status in angular

查看:23
本文介绍了预检响应在角度中没有 HTTP ok 状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务中定义了以下获取请求:

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
    });
}

结果是:

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, …}

我也向 Postman 发出了同样的发帖请求,但一切正常,所以本地服务器正常工作.

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.

推荐答案

CORS 合约要求在飞行前 OPTIONS 请求上不需要进行身份验证.看起来您的后端需要对 OPTIONS 请求和 GET 进行身份验证.

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.

当您使用 Postman 访问后端时,您只是发送了一个 GET.浏览器将首先发送一个 OPTIONS 请求(没有您的身份验证标头),并查找具有Access-Control-Allow-Origin"的响应.与发出请求的页面的来源相匹配的标头.

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.

如果对 OPTIONS 请求的响应不是 2xx,或者标头不存在,或者标头值与请求页面的来源不匹配,您将收到您遇到的错误,而 GET 请求不会制作.

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;将您的后端更改为在处理登录 url 时不需要对 OPTIONS 方法进行身份验证.

TLDR; change your back-end to not require authentication for the OPTIONS method when handling the login url.

这篇关于预检响应在角度中没有 HTTP ok 状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆