简体   繁体   中英

Angular2 http get request with header fails

I am trying to do a simple get request via angular2 http like this: (the token is present also retrieved from a post to my api)

let idToken = localStorage.getItem('id_token');
let authHeader = new Headers();
if (idToken) {
    authHeader.append('Authorization', 'Bearer ' + idToken);
}
return this._http.get('http://someapicall-to-my-custom-api', {headers: authHeader})
.map(response => response.json())
.subscribe(
    data => console.log(data),
    error => console.log(JSON.stringify(error)),
    () => console.log('Completed')
);

If i call my api without the headers it returns a good result. The moment i add the header i only runs through the error in subscribe. The problem is that i need to start sending the header with it to get some protected data and so far that is failing.

In the console i see no usefull information at all i just see this:

{"_body":{"isTrusted":true},"status":200,"ok":true,"statusText":"Ok","headers":{},"type":3,"url":null}

On the GET request to the api i see no 200 ok but i do when i didnt add the headers. Also there are no response headers.

If i try to use postman to do the same, it works without problems in that program.

I hope someone can point me into the right direction. Could it be my api? How can i debug this?

You also need

Access-Control-Allow-Headers: Authorization

See also CORS: Autorization is not allowed by Access-Control-Allow-Headers

By adding this to the routes.php in my Laravel API, which was the api i was trying to call it started to work. Thanks for Günter Zöchbauer to give me the idea to add that there :)

header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization');

In this happens in the context of electron apps and chrome extensions as well.

The cause is that there is proxy in between you app and your server. (usually an authentication proxy server for intranet domains). This new url will not match the page URL where you app was loaded from or other trusted URLs.

Unfortunately you don't know the domain on your proxy server to add it to your trusted URLs. So there is no way to fix this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM