angular.js - ionic2 浏览器跨域问题
天蓬老师
天蓬老师 2017-05-15 17:12:33
0
2
803

ionic2项目从Localhost向远程服务器提交Post请求,在真机中可以返回正确的数据,但是在Chrome中遇到了跨域的问题,查了些资料,配置了一下服务端的Access-Control-Allow,但是没效果,谁能看一下吗,下面是报错和代码。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
滿天的星座

I have also encountered this pitfall, and I have written the whole process in my blog: http://www.haoguangbo.com/arc...

To put it simply, because the access to the web page on the real machine uses the file://协议,而非http://https://,因此不会出现跨域问题,但是浏览器里开发调试的时候,由于实际上是ionic的CLI在本地跑了一个小服务器,网页等资源都是通过http加载的,就会出现跨域问题。
解决这个其实很简单,后端服务器不需要做任何处理,只需要在ionic的配置文件(ionic.config.js)里加上proxy field, as shown below:

{
  "name": "appname",
  "email": "",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "https://api.instagram.com/api"
    }
  ]
}

Then, when you want to access https://api.instagram.com/api/xxx的时候,就改成访问/api/xxx,ionic会自动把以http://localhost:8000/api开头的请求都转发到https://api.instagram.com/api,就像shadowsocks一样。
最后重新ionic serve just restart ionic.
This issue should be written into the official documentation by the ionic team. It has really tricked too many people.
Hope this helps.

某草草

Has CROS been set up in angular?

$httpProvider.defaults.withCredentials = true;

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template