请求的资源上没有“Access-Control-Allow-Origin”标头 - Ionic 2

时间:2016-06-02 18:33:39

标签: http angular xmlhttprequest ionic2

我有一个休息网络服务,现在我想从离子2前端应用程序发送请求到身份验证休息方法。

在我的登录组件上,我有:

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

在我的提供商上,我的_restClient代码是:

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);
    }

我还有一个设置标题的私有方法:

   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;
    }

我有经典的信息:

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

我做错了什么?

1 个答案:

答案 0 :(得分:1)

实际上,它是服务器端问题,而不是Angular2问题。预检的OPTIONS请求需要在其响应中返回Access-Control-Allow-Origin标头。

有关详细信息,请参阅这些文章: