问题
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
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);
}
);
}
Request missing headers
Although CORS is enabled on my server, so doesn't seem to CORS issue
回答1:
let options = {
headers: httpHeaders
};
This should be a RequestOptions object not a plain object. Angular HttpClient wont recognize it. Change it to
let options = new RequestOptions({ headers: headers });
来源:https://stackoverflow.com/questions/51467977/authorization-header-not-sent-with-http-request-angular-6-with-options-method