ionic problem No 'Access-Control-Allow-Origin'

后端 未结 4 798
独厮守ぢ
独厮守ぢ 2020-12-19 00:10

I\'m working on an ionic apps. My problem is: when I try to get data from server I got this:

XMLHttpRequest cannot load https://mywebsite.com/api. No

4条回答
  •  情歌与酒
    2020-12-19 00:56

    This is a typical error found when we work with Angular and Ionic, the problem appears because when your app loaded in a browser on your app loads all the content from an origin that comes from your local address http://localhost:8100, then when you want to make any AJAX request sent out to another host than localhost:8100 the request is called from an any point different from the origin its require a CORS(Cross Origin Resource Sharing) preflight request to see if it can access the resource.

    The solution is use a Proxy To Backend, with this you can highjack certain urls and send them to a backend server. The implementation is easy:

    1.- Modify the file ionic.config.json in the root folder of your project.

    2.- Configure your proxy, inside your ionic.config.json file put this, assuming your new host is in http://localhost:3000.

       "proxies": [
    {
      "path": "/endpoints",
      "proxyUrl": "http://localhost:3000"
    }
      ]

    3.- In your Service change a little the path of your request from this http://localhost:3000/endpoints/any/path/that/you/use to this ../endpoints/any/path/that/you/use(assuming the another host is in localhost:3000 and the context is /endpoints)

    If you need more information about this please check http://blog.ionic.io/handling-cors-issues-in-ionic/

提交回复
热议问题