请求的资源上没有“Access-Control-Allow-Origin”标头 - Ionic 2 [英] No 'Access-Control-Allow-Origin' header is present on the requested resource - Ionic 2

查看:1193
本文介绍了请求的资源上没有“Access-Control-Allow-Origin”标头 - Ionic 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我有经典信息:

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

我做错了什么?

推荐答案

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

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/

这篇关于请求的资源上没有“Access-Control-Allow-Origin”标头 - Ionic 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆