Reputation: 61
When I send a GET with HttpClient, server receives the Authorization Header. But when I send the same request using POST, Angular doesn't send the Authorization Header.
let cabecalho1 = new HttpHeaders();
cabecalho1 = cabecalho1.append("Authorization", "Basic YXBpOmViYzg3Njg5MjhiZjkljjE1NGIyMTg4NGZlMjU5MDA3NDllMGU0MTRmZGM");
cabecalho1 = cabecalho1.append("Content-Type", "application/x-www-form-urlencoded");
let url = "http://localhost/ionic/json.php";
// 'post' doesn't sends Authorization Header.
// when I change to 'get' verb, the server receives the Authorization Header.
this.httpClient.post(url,
{
headers: cabecalho1,
params: {
ola: 'mundo',
cnt: '5'
}
}).subscribe(res => {
// this.posts = res;
console.log("resposta POST:");
console.log(res);
});
Comparing POST vs GET data sent (in Yellow is the GET)
When I use Postman, the Authorization Header is received both in GET and POST in my PHP server. Why Angular 5 HttpClient doesn't send Authorization Header specifically in POST?
Upvotes: 1
Views: 473
Reputation: 453
If you look at the reference for HttpClient here, you'll see that the signature for get() is this:
get(
url: string,
options:
{
headers?: HttpHeaders | { [header: string]: string | string[]; };
observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; };
reportProgress?: boolean; responseType?: "arraybuffer" | "blob" | "text" | "json"; withCredentials?: boolean;
} = {}
): Observable<any>
and the signature for post() is this:
post(
url: string,
body: any,
options:
{
headers?: HttpHeaders | { [header: string]: string | string[]; };
observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; };
reportProgress?: boolean; responseType?: "arraybuffer" | "blob" | "text" | "json";
withCredentials?: boolean;
} = {}
): Observable<any>
as you can see, the "body" parameter of the post() method is not optional (because it does not have a '?' immediately after it), therefore is required. You were sending your headers, but they were in the body of the post request, rendering them useless.
To fix this, add an empty object for the "body" parameter, like so:
this.httpClient.post(url, {},
{
headers: cabecalho1,
params: {
ola: 'mundo',
cnt: '5'
}
}).subscribe(res => {
//
});
Upvotes: 1
Reputation: 106
Try this:
myApiFunction(id: string) {
// add authorization header with jwt token
let headers = new HttpHeaders({ 'Authorization': 'Bearer ' + this.token });
let options = { headers: headers };
return this.http.post(this.baseUrl + 'https://213.121.21.21/api/myApiFunction', id , options);
}
Upvotes: 0