0

I’m calling a service using a token

Failed to load resource: the server responded with a status of 401 (Unauthorized)

Http failure response for http://localhost:65291/api/post: 401 Unauthorized 

The same call works in Postman with Headers;

Content-Type: application/json
Authorization: Bearer token

The function in ionic is

getPosts() {
    var header = new HttpHeaders({ "Content-Type": "application/json" });
    header.append("Authorization", "Bearer " + this.token);
    console.log("Bearer " + this.token);
    return new Promise(resolve => {
      console.log(this.apiUrl + '/post');
      this.http.get(this.apiUrl + '/post', { headers: header}).subscribe((data: Post[]) => {
        resolve(data);
      }, err => {
        console.log(err);
      });
    });
  }

Added a log for the token to be sure that is adding it to the header correctly (the token is fine). The apiUrl variable has value http://localhost:65291/api.

What is wrong here? Cors is enabled… Postman works ok…

Thanks

Fiury
  • 5,540
  • 2
  • 10
  • 9
  • Do you actually see in the network tab of chrome on this request in the headers the authorization and the token? – misha130 Jul 13 '18 at 21:43
  • can u share screenshot of network tab.because i face same issue in my app also. And from your given code i m sure that no issue from your side. its error from server and Api side. – keval nayak Jul 14 '18 at 05:35
  • which http you are using? Angular 4.3+ or previous one (HttpClient or)? Since: A) Postman works and B) you are getting 401 - it hints at that this is a client forming request problem. If you can share which http module you are using I can help – Sergey Rudenko Jul 14 '18 at 16:39

3 Answers3

0

I think you definitely have client side problem (since its 401 and also you mention Postman works ok).

I had similar issues when I tried to append headers in the same fashion you did so I would suggest trying this (to eliminate this problem):

getPosts() {
        // try forming headers object in one go:
        let token = "Bearer "+this.token
        let headers = new HttpHeaders({ 
            "Content-Type": "application/json",
            "Authorization": token
        });
        // now here I am not sure why you do promise wrapping this way, but then I would suggest:
        return this.http.get(this.apiUrl + '/post', { headers: headers })
            .toPromise()
            .then((data: Post[]) => { // Success
                console.log(data);
                resolve(data);
            }, (err) => {
                console.log(err);
            });
    }

If the problem is still there - please share which version of Angular and Http module you are using?

Also check out this issue here: How to correctly set Http Request Header in Angular 2

And specifically this answer if you are on Angular 4.3+: How to correctly set Http Request Header in Angular 2

Sergey Rudenko
  • 8,809
  • 2
  • 24
  • 51
0

After a while I found the problem,

header.append("Authorization", "Bearer " + this.token); is wrong. It worked using

let headers = new HttpHeaders({"Authorization: " + "Bearer " + this.token})

Setting multiple headers:

this.http
.post('api/items/add', body, {
  headers: new HttpHeaders({
    'Authorization': 'my-auth-token',
    'x-header': 'x-value'
  })
}).subscribe()
Fiury
  • 5,540
  • 2
  • 10
  • 9
0

I had a similar problem, it works on postman and cors enabled but in the app doesn't work, my problem was i have / at the end of the URL in the API security config, and i was making the request without /, i just remove it from request URL, also you can add /* in security config or put / in your app, the URL must be the same.

(maybe you have solved your issue and it was different issue but this is a possibe solution)