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