Angular2 CORS issue

杀马特。学长 韩版系。学妹 提交于 2020-01-04 06:18:10

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/39659559/angular2-cors-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!