当我们遇到请求后台接口遇到 Access-Control-Allow-Origin 时,那说明跨域了。
跨域是因为浏览器的同源策略所导致,同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,同源是指:域名、协议、端口相同

解决跨域常用方法:
VUE中常用proxy来解决跨域问题
1、在vue.config.js中设置如下代码片段
devServer: {
port: 8001, // 端口号
open: false, //配置是否自动启动浏览器
https: false,// https:{type:Boolean}是否启用https
proxy: {
// 代理
"/prod-api": {
target: "http://192.168.130.224:8001", //董浩
// target: "http://192.168.145.106:8001", //测试
ws: false,// 是否启用websockets
changeOrigin: true,//开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite: {
"^/prod-api": ""//这里理解成用'/api'代替target里面的地址,比如我要调用'192.168.130.224:8001/user/getuserlist',直接写'/prod-api/user/getuserlist'即可
}
}
}
},
2、创捷axioss实例时,将baseUrl设置为 ‘/api’
const http = axios.create({
timeout: 1000 * 1000000,
withCredentials: true,
BASE_URL: '/api'
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
})
网友评论