【问题标题】:No 'Access-Control-Allow-Origin' header is present upon Ionic2 http post requestIonic2 http post 请求中不存在“Access-Control-Allow-Origin”标头
【发布时间】:2016-10-12 08:07:40
【问题描述】:

这是我完整的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...但我无法理解...

任何帮助将不胜感激。

【问题讨论】:

标签: javascript angularjs ionic2


【解决方案1】:

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

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 -> /mobile 来自 path 中的 ionic.config.json

【讨论】:

  • @vuhung3990 我很难完全理解您的解决方案,因为谷歌搜索诸如 GlobalEnv、AuthBody、标头、语言之类的东西并不能让我知道您正在使用什么包。你能启发我吗?也许还包括一些进口。干杯。
  • @JGFMK 嗨,你不需要知道 GlobalEnv、AuthBody、Headers 是什么意思,这是我的自定义组件,我刚刚更新了我的答案
  • 根据我对 CORS 的了解,您必须协商飞行前检查,我假设它会转到另一个 URL,并且您需要提供某种用户名和密码.他们通常会查询该身份验证过程的参数吗?如果是这样,您可以将其放入代理网址中吗?我还以为nodejs.org/api/http.html 会对此有更多详细信息
【解决方案2】:

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

【讨论】:

  • 这只是针对单个用户的短期修复
  • 它在浏览器中运行... firefox 和 blisk... 但它不适用于 Ionic2 开发环境...
猜你喜欢
  • 2019-03-08
  • 2015-12-24
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
相关资源
最近更新 更多