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反向代理解决跨域问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用js将ETH账户的资产打散其他账户web3
- 2024-09-27我轻松地将我的 React.js 应用程序翻译成了多种语言。下面是我是如何做到的... ??
- 2024-09-27?? 使用 useMemo 和 useCallback 加速 React:告别缓慢的重新渲染!??
- 2024-09-27Vue CLI多环境配置教程:新手入门指南
- 2024-09-27Vue CLI多环境配置教程:快速入门指南
- 2024-09-27Vue CLI教程:新手入门指南
- 2024-09-27Vue CLI教程:初学者快速入门指南
- 2024-09-27Vue3公共组件教程:入门与实践
- 2024-09-27Vue3公共组件教程:新手入门指南
- 2024-09-27Vue3教程:初学者快速入门指南