vue 打包部署后 如何解决其他域名的跨域问题
-
创建时间
22年8月13日
-
最后回复
22年8月17日
- 15
回复
- 294
浏览
- 2
用户
- 3
链接
vue 打包部署后 如何解决其他域名的跨域问题
可以写一个代理程序(用 Express 做就行),在里面编写 API 来请求「另外一个项目」并将得到的结果进行返回,同时借助 cors 对相关 API 进行配置以使得您的 Vue 项目可以正常访问这些 API 而不会遇到跨域问题。这个代理程序也可以部署在云引擎上(可以部署到同一个应用的不同分组)。
这边看到 Vue 应用发送请求时遇到的错误信息为:
Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
意味着您需要在 Express 应用那边向 cors 传入配置来指定接受的请求源头(不传配置的话默认就会是 *)。
具体可参考 Express 文档。
搞定了,credentials true 情况下 vue客户端需要配置 axios.defaults.withCredentials= true 需要填写指定域名
const corsOptions = {
"origin": "url链接",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204,
"credentials":true
}
credentials false 情况下 vue客户端需要配置 axios.defaults.withCredentials= false "origin": "*" 可以为通配符
const corsOptions = {
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204,
"credentials":false
}
app.use(cors(corsOptions))
或者 app.use(cors())