使用 OPTIONS 方法未随 http 请求 angular 6 发送授权标头 [英] Authorization header not sent with http request angular 6 with OPTIONS method

查看:30
本文介绍了使用 OPTIONS 方法未随 http 请求 angular 6 发送授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am getting 401 error while sending post request using the angular code, when I inspected network request I found out that the headers are not being sent along the post request, please see the image:

auth.service.ts

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 问题

Although CORS is enabled on my server, so doesn't seem to CORS issue

推荐答案

let options = {
  headers: httpHeaders
};

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

This should be a RequestOptions object not a plain object. Angular HttpClient wont recognize it. Change it to

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

这篇关于使用 OPTIONS 方法未随 http 请求 angular 6 发送授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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