No 'Access-Control-Allow-Origin' header is present on the requested resource - Ionic 2 [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-25 17:43:43

问题


I have a rest web service and now I want to make a post request from ionic 2 frontend app to authentication rest method.

On my login component I have:

...this._restClient.post(
                'authentication',
                body,
                (data) => this.handleSuccessAuthenticate(data),
                (data) => this.handleErrorAuthenticate(data)
            );...

On my provider my _restClient code is:

public post(resource: string, data: Object, onSuccess: restClient, onError: callbackRestClient) {
        var httpResult: Observable<Response>;


        if (data === null) {
            httpResult = this._http.post(this.getUrl(resource), '{}', { headers: this.getHeaders() });
        } else {
            httpResult = this._http.post(this.getUrl(resource), JSON.stringify(data), { headers: this.getHeaders() });
        }


        this.handleResult(httpResult, onSuccess, onError);
    }

I also have a private method to set headers:

   private getHeaders() {
        var headers = new Headers();
        headers.append('Accept', 'application/json');
        headers.append('Content-Type', 'application/json');
        headers.append('Access-Control-Allow-Origin', '*');
        headers.append('Access-Control-Allow-Credentials', 'true');
        headers.append("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        headers.append("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");

        return headers;
    }

I have the classic message:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

What I´m doing wrong?


回答1:


In fact, it's server-side issue and not an Angular2 one. The preflighted OPTIONS request need to return a Access-Control-Allow-Origin header in its response.

See these articles for more details:

  • http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
  • http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/


来源:https://stackoverflow.com/questions/37599655/no-access-control-allow-origin-header-is-present-on-the-requested-resource-i

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