Search code examples
angularhttp-status-code-401http-put

Angular2 HTTP put add authorization header


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.

enter image description here

Is this normal?

If I add manually in Postman the authorization header as a header the request works as expected.


Solution

  • 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......