【发布时间】: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