【问题标题】:Authorization header not sent with http request angular 6 with OPTIONS method使用 OPTIONS 方法未使用 http 请求 Angular 6 发送授权标头
【发布时间】:2018-12-30 06:24:51
【问题描述】:

我在使用 Angular 代码发送 post 请求时收到 401 错误,当我检查网络请求时,我发现标头没有随 post 请求一起发送,请看图片:

auth.service.ts

login(username: string, password: string) {
    let httpHeaders = new HttpHeaders({
      'Authorization': 'Basic bXktdHJ1c3RlZC1jbGllbnQ6c2VjcmV0',
      'Content-Type': 'application/json'
    });
    let options = {
      headers: httpHeaders
    };
    this.http.post(
      'http://localhost:8080/SpringSecurityOAuth2Example/oauth/token?grant_type=password&username=bill&password=abc123',
      null,
      options
    ).subscribe(res => {
      console.log(res);
    },
      err => {
        console.log(err);
      }
    );
}

请求缺少的标头

虽然我的服务器上启用了 CORS,但似乎不是 CORS 问题

【问题讨论】:

  • 问题中的请求标头似乎是浏览器自动发送的 CORS preflight OPTIONS 请求。不包含 Authorization 标头的原因是 CORS 规范要求浏览器从不发送 Authorization 标头或任何其他凭据作为预检 OPTIONS 请求的一部分。因此,如果您发送请求的服务器必须允许未经身份验证的 OPTIONS 请求 - 不需要 Authorization 标头 - 如果不允许,则预检将失败并且浏览器仍然停在那里,甚至从不尝试来自您的 POST 请求代码。
  • @sideshowbarker 感谢您指出,我进行了更改以跳过 OPTIONS 方法的身份验证并且它有效。你拯救了我的一天!

标签: angular cors http-headers angular6


【解决方案1】:
let options = {
  headers: httpHeaders
};

这应该是 RequestOptions 对象而不是普通对象。 Angular HttpClient 无法识别它。改成

let options = new RequestOptions({ headers: headers });

【讨论】:

  • RequestOptions 已弃用 Angular 6
猜你喜欢
  • 2022-10-16
  • 1970-01-01
  • 2018-01-27
  • 2017-06-01
  • 2016-06-27
  • 2010-11-23
  • 2019-05-29
  • 2019-02-03
  • 2014-09-25
相关资源
最近更新 更多