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);
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM