CORS issue with Vue.js

佐手、 提交于 2019-11-30 10:03:10

While you can add Access-Control-Allow-Origin: * to your server response (in this case IIS) but this is very much advised against.

What's happening here is that your client is http://localhost and it is trying to access https://mywebsite/api/ which means they're not from the same origin

If you add Access-Control-Allow-Origin: * you will be allowing the entire world to hit your API endpoint.

I'd suggest making your access control server headers Access-Control-Allow-Origin: *.mysite and make a vhost for your localhost to use dev.mysite or similar.

This will allow your "localhost" to access your API without issues.

You could also add localhost to a whitelist, but this is also not without its own security implications, and it doesn't work everywhere anyway.

So, in short, make a vhost for your localhost that's in the same domain as your REST service and your issue should be resolved.

Once you go live you should remove the *.mysite part and use as specific a domain as possible on your whitelist.

Good luck!

Greater possibility is that CORS is not enabled on the IIS. This can be enabled by modifying the web.config file in the application root folder in IIS as follows:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
   <httpProtocol>
         <customHeaders>
           <add name="Access-Control-Allow-Origin" value="*" />
         </customHeaders>
   </httpProtocol>

</system.webServer>
</configuration>

Note: This method will allow anyone to reach the API endpoint and hence shouldn't be adopted on a production environment but only on a development environment.

1) Be sure that server sends Access-Control-Allow-Origin "*" header.

2) Vue.http.headers.common['Access-Control-Allow-Origin'] = true, Vue.http.headers.common['Access-Control-Allow-Origin'] = '*' and etc. don't needed in the client request.

3) Vue.http.options.emulateJSON = true should helps if 1 and 2 points already are ok, but vue-resource fails with status 0. Also, try to remove (if they exist) Vue.http.options.credentials = true and Vue.http.options.emulateHTTP = true.

Or you can bypass it for development purpose by using chrome CORS extension. Works with codesandbox

You face this error when the API url and client url aren't the same. Vue CLI 3 (and in the core of it, Webpack) allows you to proxy your API url to your client url.

Inside vue.config.js file add following lines:

// vue.config.js
module.exports = {
  // options...
  devServer: {
        proxy: 'https://mywebsite/',
    }
}

And then send your ajax calls to http://localhost/api/.

You can read the full article here: How to deal with CORS error on Vue CLI 3?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!