I am trying to send http get request on angular.
how do I add apikey on Authorization, I am able to that only on Postman since you just put values.
this.http
.get(url)
.pipe()
.subscribe((data: any) => {
console.log(data);
});
when I send this request, it says unauthorized because api key missing
CodePudding user response:
It is possible to add headers to a request using HttpHeaders
:
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
and you can pass them like this:
this.http.get(url, { headers }) // ...
CodePudding user response:
Try with below code :
let header = new HttpHeaders().set(
"Authorization",
localStorage.getItem("token")
);
return this.http.get(url, {headers:header}).pipe()
.subscribe((data: any) => {
console.log(data);
});
CodePudding user response:
- Check first if the apiKey is return from the Backend when you execute the auth request
- If yes you need to execute first the auth request in Angular (POST REQUEST): enter the login paramer and you will receive the token/apiKey.
constructor(private http: HttpClient, private router: Router) {} // in Component (server: 'http://localhost:5000/api) // in environment.ts
***login(user: { username: string, password: string }): Observable<boolean> {
return this.http.post<any>(`${environment.server}/auth`, user)
.pipe(
tap(tokens => this.doLoginUser(user.username, tokens)),
mapTo(true),
catchError(error => {
console.log(error.error);
return of(false);
}));
}***
Use this Token to get specifical data from the db
public getUserInfos() { return JSON.parse(localStorage.getItem(this.USER_INFOS)); }
I hope I could help