Remus
Remus

Reputation: 179

Angular2 CORS issue

I'm new to angular2 and to be fair I have very few knowledges which I try to fix, however I've run into some issues about cross site request, trying to access a service from another application but I have this issue whatever I try to do

XMLHttpRequest cannot load https://hr/Team/EditEmployeeInfo.aspx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54396' is therefore not allowed access. The response had HTTP status code 401.

This is my angular2 service and I've tried something like this

getUserHrtbProfile(userId): Promise<any> {            
        const headers = new Headers();
        headers.append('Access-Control-Allow-Headers', 'Content-Type');
        headers.append('Access-Control-Allow-Methods', 'GET, PUT, POST, DELET');
        headers.append('Access-Control-Allow-Origin', '*');

        var apiUri: string = "https://hrtb/Team/EditEmployeeInfo.aspx?emplid={0}&Menu=InfoEmployee&T=0".replace("{0}", userId);
        return this.http.get(apiUri, headers).map(result => result.json()).toPromise();
}

and this is my component

this.bannerService.getUserHrtbProfile(this.userId).then(hrtbJson => {
    this.hasHrtbAccess = hrtbJson.HasHrtbAccess;
    this.hrtbProfileUrl = hrtbJson.HrtbProfileUrl;
}).catch(err => {
    this.hasHrtbAccess = false;
});

I've search a solution on my problem but still could not find one that suits my need.

Angular 2 http request with Access-Control-Allow-Origin set to *

But most important, is this an angular2 problem that I need to solve? Or in fact as I've read it should have been handled by the team that exposes the API?
Thank you all.

Upvotes: 2

Views: 667

Answers (2)

Elio Salvatore
Elio Salvatore

Reputation: 51

You need to enable CORS on your API backend. Only for testing purpose you could use this Chrome Extension to simulate CORS on your api backend:

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Upvotes: 1

Bharat
Bharat

Reputation: 2464

You are trying to make request on other domain, this is what you can not resolve here. try with making request at you backed code, this will resolve you issue.

Upvotes: 0

Related Questions