Reputation: 213
I am trying to use http put in Angular. My code looks like this:
const url ='this is my url';
const headers = new Headers({'Authorization': 'this is my token'});
return this.http.put(url, {headers: headers}).toPromise().then......
But I keep getting 401 Unauthorized as request status code. I tried to copy my request from Chrome Network tab to Postman, and I noticed that the authorization header was added to the request body, not to the headers.
Is this normal?
If I add manually in Postman the authorization header as a header the request works as expected.
Upvotes: 3
Views: 1967
Reputation: 755
https://angular.io/guide/http#adding-headers
When I use httpclient in angular2+ framework, I usually use like this :
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
Did you check Content-Type
in headers?
if you want to add set auth header in service layer, when you call httpClient, you can use Http interceptor ( https://alligator.io/angular/httpclient-interceptors/ )
Upvotes: 0
Reputation: 26084
According to the docs https://angular.io/api/http/Http
Http.put method signature is:
put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>
So, your second parameter should be the data/body, not the options.
Try:
return this.http.put(url, {}, {headers: headers}).toPromise().then......
Upvotes: 4
Reputation: 1905
When you do a PUT
request you need to provide a body, because right now you are passing the headers
as the body in your request. So your request would be something like
this.http.put(url, body, headers)
Upvotes: 2