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

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

问题描述

我在服务中定义了以下get请求:

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.

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

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