我在用着:
- Vue 2.0.3
- Vue路由器2.0.1
- Vuex 0.8.2
- Vue 资源 0.7.0
在尝试使用远程 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.
现在我在 Azure 中运行了 API,因为它允许我测试来自 Postman 的调用,所以我很确定 CORS 标头在后端已正确设置。对 Vue 和前端不太确定。
我在配置文件中有这样的情况:
export const API_ROOT = 'https://mywebsite/api/'
export const AuthResource = Vue.resource(API_ROOT + 'auth{/action}')
比即我称这个动作为:
login: function (userData) {
return AuthResource.save({action: 'login'}, userData)
}
最后,当我通过 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
}
}
我试过在这里添加 Vue.http.headers.common['Access-Control-Allow-Origin'] = true
,但没有帮助。
任何想法?我做错了什么..我想如果它不适用于登录,它也不适用于其他呼叫。
原文由 desicne 发布,翻译遵循 CC BY-SA 4.0 许可协议
当 API url 和客户端 url 不同时,您会遇到此错误。 Vue CLI 3(以及它的核心,Webpack)允许你将你的 API url 代理到你的客户端 url。
在
vue.config.js
文件中添加以下行:然后将您的 ajax 调用发送到
http://localhost/api/
。您可以在此处阅读完整文章: 如何处理 Vue CLI 3 上的 CORS 错误?