处理离子中的CORS问题 [英] Handling CORS Issues in Ionic

查看:103
本文介绍了处理离子中的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用myApiserver脚本创建一个API,并且正在尝试与我正在处理的IONIC框架应用程序上的api进行通信,但它一直在提出跨源阻塞错误),您可以在Ionic应用程序中创建代理别名路由API调用,完全避免 origin 问题,但是,他们的指南特定于Ionic 1,所以这里是Ionic v2的更新。



在Ionic v2中创建代理



打开 ionic.config.json 并添加以下代理设置。

  {
name:project-name,
app_id:xyz- projectid,
v2:true,
typescript:true,
proxies:[{
path:/ api,
proxyUrl:https://the-real-api-host.com
}]
}

在这个例子中,我们在离子应用程序中创建一个 / api 的路径,它将请求转发到端点 https://the-real-api-host.com
如果你想使用不同的api端点,例如 http://my-custom-api.com/api/v2/ ,你可以插入它改为 proxyUrl



更新API端点的引用



在您的应用程序代码中,您现在需要在 https://the-real-api-host.com 更新API端点的基本URL的所有引用使用 / api 。在Ionic服务时,应检测到对 / api 的调用,并代理到真实地址。



每个项目实施可能有所不同在我的情况下,我没有控制API,因为它是一个外部服务,所以我无法自己控制CORS处理/响应。


i am creating an API with ourApiserver script and am trying to communicate with the api on IONIC framework application i am working on but it keeps on bringing up the cross-origin blocked error

解决方案

When developing locally using ionic serve or ionic run/emulate -l -c with livereload enabled, ionic creates a local dev server at port 8100 by default (http://localhost:8100/ ). The origin in this case is localhost:8100 , which when you contact an external service via HTTP with CORS enabled, they deem the request not trustworthy and therefor reject it.

As suggested by Ionic themselves (http://blog.ionic.io/handling-cors-issues-in-ionic/) , you can create a proxy alias within the Ionic app to route the API calls via, avoiding the origin issue altogether, however, their guide was specific for Ionic 1, so here is an update for Ionic v2.

Creating a Proxy in Ionic v2

Open ionic.config.json and add in the following proxies setup.

{
  "name": "project-name",
  "app_id": "xyz-projectid",
  "v2": true,
  "typescript": true,
  "proxies": [{
    "path": "/api",
    "proxyUrl": "https://the-real-api-host.com"
  }]
}

In this instance, we are creating a path within the ionic app at /api ,which will forward requests to the endpoint https://the-real-api-host.com . If you wanted to use a different api endpoint, for example http://my-custom-api.com/api/v2/ , you could insert it into proxyUrl instead.

Updating References to API Endpoint

In your app code, you now need to update all the references of the base URL for the API endpoint at https://the-real-api-host.com with /api . A call to /api should be detected when in Ionic serve, and proxied to the real address.

Each projects implementation may vary. In my case, I did not have control of the API, as it was an external service, so I could not control the CORS handling/responses myself.

这篇关于处理离子中的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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