Vue axios 配置请求后端多个地址
地址管理url.js
module.exports = {
domain: {
Base_M1_URL: 'http://127.0.0.1:8014',
Base_M2_URL: 'http://127.0.0.1:8015',
}
}
main.js配置
import axios from 'axios'
import {
domain
} from './utils/url.js'
axios.defaults.baseM1URL = domain.Base_M1_URL;
axios.defaults.baseM2URL = domain.Base_M2_URL;
分装Post、Get请求common.js
import axios from 'axios'
axios.defaults.timeout = 180000
function paramsToUrl(url, params) {
if (!params) return url
for (var key in params) {
if (params[key] && params[key] != 'undefined') {
if (url.indexOf('?') != -1) {
url += '&' + '' + key + '=' + params[key] || '' + ''
} else {
url += '?' + '' + key + '=' + params[key] || '' + ''
}
}
}
return url
}
export function requireData(url, params, type, item) {
debugger;
if (!url) return false
switch (item) {
case 'back':
url = axios.defaults.baseM1URL + url
break;
case 'before':
url = axios.defaults.baseM2URL + url
break;
default:
url = axios.defaults.baseM2URL + url
}
if (type === 'get') {
url = paramsToUrl(url, params)
return new Promise((resolve, reject) => {
axios.get(url, params).then(res => {
resolve(res.data)
}).catch(err => {
reject(err)
})
})
} else {
return new Promise((resolve, reject) => {
axios.post(url, params).then(res => {
resolve(res.data)
}).catch(err => {
reject(err)
})
})
}
}
使用封装的方法
created(){
test1('/test/tes1','null','post','before').then(res =>{
if(res.code == 200){
alert(res.body)
}else{
alert(res.body)
}
})
}
created(){
test1('/test/tes1','null','post','before').then(res =>{
if(res.code == 200){
alert(res.body)
}else{
alert(res.body)
}
})
}