2021-04-06 vue cli4配置代理解决跨域问题

同源策略和跨域

参考:
同源策略和跨域解决方案
MDN跨域资源共享CORS

同源:协议、域名、端口相同。
以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-cli4 如何配置代理跨域【附代码】.

  1. 在项目根目录下新建vue.config.js文件。
    vue cli4和cli3中对于config文件不进行显示,所以需要手动新建config文件配置。
    在这里插入图片描述
  2. 配置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中的地址
            	}
        	}
      	}
    }
}
  1. 加/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中的地址
            	}
        	}
      	}
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值