in my Angular project I am using the HttpClient (@angular/common/http). I am successfully doing lots of API requests with POST, GET and DELETE methods, always to the same backend URL and including the same headers (Bearer Authentication). As soon as I am doing a PATCH request (same URL, same headers), the server complains with a "401 Unauthorized" status. I checked if the headers are correctly send with the PATCH, but they are not. When using the following code snippet for the request the headers I am sending are somehow set in the lazyUpdate section of the Headers (but only for PATCH. POST, GET, DELETE work fine), which is not correct:
let headers = new HttpHeaders();
headers = headers.
set('content-type', 'application/json').
set('Authorization', 'Bearer <myToken>');
this.httpClient.patch(<my_patch_url>, { 'headers': headers });
On the other hand, when using the following code, the headers are set correctly, but still somehow not recognized:
const headers = {
'content-type': 'application/json',
'Authorization': 'Bearer <myToken>')
}
this.httpClient.patch(<my_patch_url>, { 'headers': headers });
So it works all fine except for the PATCH request.
Anyone any idea why PATCH is sending the headers in the wrong way?
Thanks in advance. Cheers
I found the solution to this problem myself:
It is not about how you add the header but that a request with the PATCH method additionally could need a body which reflects the parameters that should actually be updated (@param body — The resources to edit).
See definition of PATCH:
(method) HttpClient.patch(url: string, body: any, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
This works:
const headers = {
'content-type': 'application/json',
'Authorization': 'Bearer <myToken>')
}
this.httpClient.patch(patch_url, "", { 'headers': headers });
In my case the body part is empty ("") since the backend does not accept anything else.