简体   繁体   English

Vue.js 的 CORS 问题

[英]CORS issue with Vue.js

I'm using:我正在使用:

  • Vue 2.0.3 Vue 2.0.3
  • vue-router 2.0.1 Vue 路由器 2.0.1
  • vuex 0.8.2 Vuex 0.8.2
  • vue-resource 0.7.0 Vue 资源 0.7.0

And after trying to login to my page when using remote API, not the locally run one, I get cors error like following在使用远程 API 而非本地运行 API 时尝试登录我的页面后,我收到如下 cors 错误

vue-resource.common.js?2f13:1074 OPTIONS 

https://mywebsite/api/auth/login 

(anonymous function) @     vue-resource.common.js?2f13:1074
Promise$1            @     vue-resource.common.js?2f13:681
xhrClient            @     vue-resource.common.js?2f13:1033
Client               @     vue-resource.common.js?2f13:1080
(anonymous function) @     vue-resource.common.js?2f13:1008


XMLHttpRequest cannot load https://mywebsite/api/auth/login. 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://localhost:8080' is therefore not allowed 
access. The response had HTTP status code 415.

Now I have API running in Azure, and since it allows me to test my calls from Postman, I am quite sure the CORS headers are set properly on backend.现在我在 Azure 中运行了 API,并且由于它允许我测试来自 Postman 的调用,我非常确定在后端正确设置了 CORS 标头。 Not so sure about the Vue and the front.对 Vue 和前端不太确定。

I have situation like this in config files:我在配置文件中有这样的情况:

export const API_ROOT = 'https://mywebsite/api/'
export const AuthResource = Vue.resource(API_ROOT + 'auth{/action}')

than ie I am calling this action like:比即我称此操作为:

login: function (userData) {
    return AuthResource.save({action: 'login'}, userData)
}

Finally as I am checking auth in login via token in vuex submodule I have just a simple header check-up state.最后,当我通过 vuex 子模块中的令牌在登录中检查身份验证时,我只有一个简单的标头检查状态。

var updateAuthHeaders = () => {
    var token = JSON.parse(localStorage.getItem("auth_token"))
    if (token != null){
        Vue.http.headers.common['Authorization'] = token
    }else{
        Vue.http.headers.common['Authorization'] = null
    }
}

I have tried adding Vue.http.headers.common['Access-Control-Allow-Origin'] = true here, but did not help the case.我曾尝试在Vue.http.headers.common['Access-Control-Allow-Origin'] = true添加Vue.http.headers.common['Access-Control-Allow-Origin'] = true ,但没有帮助。

Any idea?有什么想法吗? What am I doing wrong.. I suppose it will not work for other calls also if it doesn't work for login.我做错了什么..我想如果它不适用于登录,它也不适用于其他调用。

You face this error when the API url and client url aren't the same.当 API url 和客户端 url 不同时,您会遇到此错误。 Vue CLI 3 (and in the core of it, Webpack) allows you to proxy your API url to your client url. Vue CLI 3(以及它的核心是 Webpack)允许您将 API url 代理到您的客户端 url。

Inside vue.config.js file add following lines:vue.config.js文件中添加以下几行:

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

And then send your ajax calls to http://localhost/api/ .然后将您的 ajax 调用发送到http://localhost/api/

You can read the full article here: How to deal with CORS error on Vue CLI 3?您可以在此处阅读全文: 如何处理 Vue CLI 3 上的 CORS 错误?

While you can add Access-Control-Allow-Origin: * to your server response (in this case IIS) but this is very much advised against.虽然您可以将Access-Control-Allow-Origin: *到您的服务器响应(在本例中为 IIS),但强烈建议不要这样做。

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这里发生的事情是您的客户端http://localhost并且它正在尝试访问https://mywebsite/api/这意味着它们来自不同的来源

If you add Access-Control-Allow-Origin: * you will be allowing the entire world to hit your API endpoint.如果您添加Access-Control-Allow-Origin: *您将允许整个世界访问您的 API 端点。

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.我建议让您的访问控制服务器标头Access-Control-Allow-Origin: *.mysite并为您的localhost主机创建一个 vhost 以使用dev.mysite或类似的。

This will allow your "localhost" to access your API without issues.这将允许您的“本地主机”毫无问题地访问您的 API。

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.您也可以将localhost添加到白名单中,但这也并非没有其自身的安全隐患,并且无论如何它都无法在任何地方工作

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.因此,简而言之,为与 REST 服务位于同一域中的本地主机创建一个虚拟主机,您的问题应该得到解决。

Once you go live you should remove the *.mysite part and use as specific a domain as possible on your whitelist.上线后,您应该删除*.mysite部分,并在白名单中尽可能使用特定的域。

Good luck!祝你好运!

1) Be sure that server sends Access-Control-Allow-Origin "*" header. 1) 确保服务器发送Access-Control-Allow-Origin "*"标头。

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. 2) Vue.http.headers.common['Access-Control-Allow-Origin'] = true , Vue.http.headers.common['Access-Control-Allow-Origin'] = '*'等等t 在客户端请求中需要。

3) Vue.http.options.emulateJSON = true should helps if 1 and 2 points already are ok, but vue-resource fails with status 0 . 3) Vue.http.options.emulateJSON = true如果 1 点和 2 点已经没问题,应该会Vue.http.options.emulateJSON = true帮助,但 vue-resource 失败, status 0 Also, try to remove (if they exist) Vue.http.options.credentials = true and Vue.http.options.emulateHTTP = true .此外,尝试删除(如果存在) Vue.http.options.credentials = trueVue.http.options.emulateHTTP = true

Greater possibility is that CORS is not enabled on the IIS.更大的可能是 IIS 上没有启用 CORS。 This can be enabled by modifying the web.config file in the application root folder in IIS as follows:这可以通过修改 IIS 中应用程序根文件夹中的 web.config 文件来启用,如下所示:

<?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.注意:此方法将允许任何人访问 API 端点,因此不应在生产环境中采用,而应在开发环境中采用。

You need a vue.config.js file at the root of your project and inside of the vue.config file you need to define your proxy within a devServer object module.exports = { devServer: { proxy: 'https://exampledomain.com/api/'}};您需要在项目根目录和 vue.config 文件中使用 vue.config.js 文件,您需要在 devServer 对象module.exports = { devServer: { proxy: 'https://exampledomain.com/api/'}}; . . Within your axios.post you can now make request by simply doing https://exampledomain.com/api/login在您的 axios.post 中,您现在只需执行https://exampledomain.com/api/login即可发出请求

vue.config.js 文件的图片

Or you can bypass it for development purpose by using chrome CORS extension. 或者您可以使用chrome CORS扩展来绕过它以进行开发。 Works with codesandbox 使用codesandbox

Just attach these in the response to your all API's只需将这些附加到您所有 API 的响应中

res.header('Access-Control-Allow-Origin','*'); res.header('Access-Control-Allow-Origin','*');

res.header('Access-Control-Allow-Methods','GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.header('Access-Control-Allow-Methods','GET, POST, OPTIONS, PUT, PATCH, DELETE');

res.header('Access-Control-Allow-Headers','Origin,Content-Type,X-Requested-With,Accept,Authorization'); res.header('Access-Control-Allow-Headers','Origin,Content-Type,X-Requested-With,Accept,Authorization');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM