Reputation: 71
I am trying to make a request in Angular with authorization with a bearer token. If I make the request in Postman, it works. But if I make it from Angular, it gives me the 401 Unauthorized
http error.
I am sure that the localstorage.getItem('auth_token')
is returning the right token, because I have logged it before to check.
const httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'application/json' ,
Authorization: 'Bearer '+ localStorage.getItem('auth_token')})
};
This is the request I am trying to make that works on postman :
getProducts(): Observable<string[]> {
console.log(localStorage.getItem('auth_token'));
return this.http.get<string[]>(this.productsURL)
.pipe(
tap(_ => this.log('fetched products')),
catchError(this.handleError('getProducts', []))
);
}
Upvotes: 1
Views: 1277
Reputation: 8597
Your problem is the fact you're not using the created headers.
Your code should look like this:
return this.http.get<string[]>(this.productsURL, httpOptions)
.pipe(
tap(_ => this.log('fetched products')),
catchError(this.handleError('getProducts', []))
);
Notice the .get
constructor - apart from passing the URL, it also passed the httpOptions
object you created the the bearer token in.
Upvotes: 3