Issue
I am currently getting a 401 unauthorized error in the console for trying to access an API endpoint I built, which is protected. I noticed that I did not add the bearer token to the header.
I noticed this and added this in however I am still getting the 401 error, what am I doing wrong? I know the token is valid because I am testing in Postman and I get a 200 response code in Postman, but 401 in Angular.
Here is my code:
let token = localstorage.get('token');
getCategories() : Observable<any> {
let token = localStorage.getItem("token");
const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
headers.set('Authorization', `Bearer ${token}`);
return this.http.get(this.CategoriesUrl, { headers: headers} )
}
Solution
The instances of the new HttpHeader class are immutable objects. Invoking class methods will return a new instance as result. So , you need to do the following:
let headers = new HttpHeaders();
header = header.set('Auth', 'Bearer ' + token )
Answered By - Nimród.Barabás
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.