Ionic2 http post请求时不存在“Access-Control-Allow-Origin”标头

时间:2016-06-11 12:32:53

标签: javascript angularjs ionic2

这是我的完整code ...

this.http.post(link, data, { headers: headers })
   .map(res => res.json())
   .subscribe(data => {
       this.data.response = data._body;
    }, error => {
        console.log("Oooops!");
    });

运行代码后出现此错误:

"XMLHttpRequest cannot load 
https://script.google.com/macros/s/AKfycbzdHHKBmLWJYZtFGlJGOrUwlPIWXor1geEOgcSgvhs/dev.     
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:8100' is therefore not allowed access. 
The response had HTTP status code 401."

我搜索了 CORS ...但我无法理解它......

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

我有同样的问题,但经过几个小时的搜索我的问题就消失了。

ionic.config.json

{
  "name": "KickStarter",
  "app_id": "85ff0666",
  "v2": true,
  "typescript": true,
  "proxies": [
    {
      "path": "/mobile",
      "proxyUrl": "http://xxxxx:port/mobile"
    }
  ]
}

你应该使用ionic g provider [name-of-provider] --ts它会生成提供者来发出这样的请求:

export class AuthProvider {
    data: any = null;

    constructor(public http: Http) { }

    load() {
        if (this.data) {
            // already loaded data
            return Promise.resolve(this.data);
        }

        // don't have the data yet
        return new Promise(resolve => {
            // We're using Angular Http provider to request the data,
            // then on the response it'll map the JSON data to a parsed JS object.
            // Next we process the data and resolve the promise wi new data.
            this.http.get('/mobile/api/authentication')
                .map(res => res.json())
                .subscribe(data => {
                    // we've got back the raw data, now generate the core schedule data
                    // and save the data for later reference
                    resolve(this.data);
                });
        });
    }
}

请记住:/mobile/api/authentication - >来自/mobilepath的{​​{1}}。

答案 1 :(得分:-3)

从谷歌浏览器下载Allow-Control-Allow-Origin应用程序。在已安装的应用程序中启用CORS并执行代码。这将暂时允许您浏览器中的CORS。