vue反向代理解决跨域问题

2021/4/15 18:58:29

本文主要是介绍vue反向代理解决跨域问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

vue-cli2

proxyTable: {
// proxy all requests starting with /api to jsonplaceholder
'/api': {
target: 'http://localhost:1337', //目标服务器,注意要到端口号
changeOrigin: true, //是否跨域
pathRewrite: {
'^/api': '' //重写api使得 /api/login -> http://localhost:1337/login等等,这里好多csdn博主跟我的不一样,可能个人喜好问题,只要映射到相应的url就行了
}
}
},

 

vue-cli3
先安装插件

npm add @cnamts/vue-cli-plugin-proxy # OR npm install @cnamts/vue-cli-plugin-proxy

 

假设请求地址是:http:www/baidu.com/api

在项目根目录下的vue.config.js(没有就新建)

module.exports = {
//反向代理,跨域
pluginOptions: {
//反向代理,跨域
proxy: {
enabled: true,
context: '/api', //必填,与下面的koi无关联,只是命名
options: {
target: 'http:www/baidu.com/',
changeOrigin: true, //是否跨域
// ws:true, //websocket
pathRewrite:{
// '^/koi':'',
// '^/koi/others':'/others'
}
}
}
}
}

 

全局使用,在mian.js

Vue.prototype.$axios = axios
axios.defaults.baseURL = "/api"

Vue.prototype.HOST = "/api"

 

需要发请求的页面

this.$axios.get(`/...?${e}`)
.then(res => {
if(res.data.code===200){

}
})
.catch(err => {
console.log(err);
})

let url = this.HOST+"/...";
this.$axios.get(`/...?${e}`)
.then(res => {
if(res.data.code===200){

}
})
.catch(err => {
console.log(err);
})



这篇关于vue反向代理解决跨域问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程