vue cli4配置代理解决跨域问题
同源策略和跨域
同源:协议、域名、端口相同。
以http://222.87.222.222:8000/index的地址为例,下列地址是否与其同源
地址 | 是否同源 | 原因 |
---|---|---|
http://222.87.222.222:8000/demo | 是 | 域名、协议、端口相同 |
https://222.87.222.222:8000/demo | 否 | 协议不同 |
http://222.87.222.211:8000/demo | 否 | 域名不同 |
http://222.87.222.222:10000/demo | 否 | 端口不同 |
跨域:当访问不同源的地址时需要跨域操作
vue cli4中配置代理服务器解决跨域
- 在项目根目录下新建vue.config.js文件。
vue cli4和cli3中对于config文件不进行显示,所以需要手动新建config文件配置。
- 配置vue.config.js文件中的代理服务器,记住配置完了vue.config.js后要重启一下才能生效
module.exports = {
devServer: {
proxy: {
'/api':{
target:'http://222.87.222.222:8000/',//别忘记加协议!!如http://
secure: false, // 如果是 https ,需要开启这个选项
changeOrigin: true,//开启跨域
pathRewrite: {
'^/api': '/'//正则匹配,相当于用api替换target中的地址
}
}
}
}
}
- 加/api
方法一:在vue.config.js中的module.exports内再加一行,,因为配置了代理服务器请求再被转发
publicPath: process.env.NODE_ENV === "production" ? './' : '/api',
//调试时,请求地址变成http://localhost:5000/api/url
//请求被转发到http://222.87.222.222:8000/url
方法二:在main.js中配置axios的默认 baseURL (不过感觉这是vue cli3的写法)
//vue cli3中main.js配置axios
import axios from 'axios'
axios.defaults.baseURL='/api';
Vue.prototype.$axios = axios
//vue cli3使用axios
this.$axios({
url:url,
method: 'get',
//按需写data,params,headers...
})
.then((res) =>{
console.log(res)
})
.catch((err) =>{
console.log(err)
})
//vue cli4中main.js配置axios,没有测试过
import axios from 'axios'
axios.defaults.baseURL='/api'
const app = createApp(App)
app.use(VueAxios, axios)// 必不可少
//vue.cli4中使用axios
this.axios({
url:url,
method: 'get',
//按需写data,params,headers...
})
.then((res) =>{
console.log(res)
})
.catch((err) =>{
console.log(err)
})
方法三:直接在axios请求中加上/api(以vue cli4为例)
this.axios({
url:url,
method: 'get',
baseURL:'/api'
//按需写data,params,headers...
})
.then((res) =>{
console.log(res)
})
.catch((err) =>{
console.log(err)
})
vue cli4中配置多个跨域
配置vue.config.js文件中的代理服务器
module.exports = {
devServer: {
proxy: {
'/api2':{//这个优先匹配,写在前面
target:'http://222.87.222.222:1000/',
https: false, // 如果是 https ,需要开启这个选项
changeOrigin: true,//开启跨域
pathRewrite: {
'^/api2': '/'//正则匹配
}
},
'/api':{
target:'http://222.87.222.222:8000/',
secure: false,
changeOrigin: true,
pathRewrite: {
'^/api': '/'//正则匹配,相当于用api替换target中的地址
}
}
}
}
}