vue项目中,配置多个接口请求基准路径url地址
【需求】——一个前端项目需要搭配两个服务端接口
一、解决方案
1.1 描述接口context-path
后端的两个接口服务请求前缀,如下:
前缀1: /mini-rest
前缀2: /
1.2 vue.config.js配置
devServer: {
port: 8005,
proxy: {
// 第一台服务器配置
'/mini-rest': {
target: 'http://localhost:8085',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/mini-rest': '/mini-rest'
}
},
// 第二台服务器配置
'/': {
target: 'http://localhost:8899',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/': '/'
}
}
}
}
1.3 axios修改
// api base_url,设置前缀不存在
const BASE_URL = ''
// 创建 axios 实例
const service = axios.create({
baseURL: BASE_URL,
timeout: 6000 // 请求超时时间
})
此时axios不需要直接指定baseUrl配置
1.4 发送请求
// 请求前缀为“/”
dibootApi.get("/trans").then(res => {
console.log('/', res)
}).catch(err => {
console.log(err)
})
// 请求前缀为“mini-rest”
dibootApi.get("/mini-rest/getTest").then(res => {
console.log('/mini-rest', res)
}).catch(err => {
console.log(err)
})
注:请求的时候手动加上前缀
1.5 结果展示
总结
多个接口服务的情况下,如果前缀是"/",要将其放在proxy配置的最后一部分,代理的时候是从上往下查找的,如果放在最上面其他服务也会被该配置代理掉
二、实例
1、src/api/index.js
// 配置项目的axios,导出进行全局配置
// 基准地址
// axios.defaults.baseURL =
// 'http://10.88.155.43/tkweb-legal-platform/lumen/public/rest/'
import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import store from '@/store'
import router from '../router'
const config = {
// baseURL在此处省略配置,考虑到项目可能由多人协作完成开发,域名也各不相同,此处通过对api的抽离,域名单独配置在base.js中
// 请求超时时间
timeout: 60 * 1000,
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// baseURL: 'http://10.88.155.43/takweb-legal-platform/lumen/public/rest/',
//本地验证接口时用
baseURL: '/api/',
//开发机验证接口时用
// baseURL: '/rest/',
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// 跨域请求时是否需要凭证
// withCredentials: true, // Check cross-site Access-Control
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'Access-Control-Allow-Origin': '*'
}
}
// 创建实例
const _axios = axios.create(config)
// 请求拦截器
_axios.interceptors.request.use(
function (config) {
// 从vuex里获取token
// const token = store.state.token
// // 如果token存在就在请求头里添加
// token && (config.headers.token = token)
return config
},
function (error) {
// // Do something with request error
// error.data = {}
// error.data.msg = '服务器异常'
return Promise.reject(error)
}
)
// 响应拦截器
_axios.interceptors.response.use(
function (response) {
// 清除本地存储中的token,如果需要刷新token,在这里通过旧的token跟服务器换新token,将新的token设置的vuex中
//console.log('haha', repsonse)
//if(response.data.code===401){
// localStorage.removeItem("token");
//delete storage.token;
//}
// 只返回response中的data数据
return response.data
},
function (error) {
if (error) {
// 请求已发出,但不在2xx范围内
// errorHandle(error.status,error.data.msg);
if (error.response.status == '401') {
if (store.getters['auth/isLoggedIn']) {
delete localStorage.token;
store.dispatch('auth/login_status_change');
} else {
store.dispatch('auth/login_status_change');
}
router.currentRoute.path !== '/login' &&
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
});
//store.dispatch('auth/gotoLogin');
}
return Promise.reject(error)
} else {
// 断网
return Promise.reject(error)
}
}
)
/**
* get 请求方法
* @param url
* @param data
* @returns {Promise}
*/
const get = (url, data = {}) => {
return new Promise((resolve, reject) => {
_axios.get(url, {
params: data
}).then(
response => {
resolve(response)
},
err => {
if (err.response.status == '401') {
if (store.getters['auth/isLoggedIn']) {
delete localStorage.token;
store.dispatch('auth/login_status_change');
} else {
store.dispatch('auth/login_status_change');
}
router.currentRoute.path !== '/login' &&
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
});
}
/*| err.response.status == '405'
if(err.response.status == 401){
localStorage.removeItem("token");
}
if (store.getters['auth/isLoggedIn']) {
store.dispatch('auth/logout');
this.$router.push({path:'/login', query: {redirect:this.$route.fullPath}});
}
*/
reject(err)
}
)
})
}
/**
* post 请求方法
* @param url
* @param data
* @returns {Promise}
*/
const post = (url, params) => {
return new Promise((resolve, reject) => {
_axios.post(url, qs.stringify(params))
.then(
response => {
resolve(response)
},
err => {
reject(err)
}
)
})
}
// DELETE 方法封装
// export const deleteRequest = (url) => {
// return axios({
// method: 'delete',
// url: url
// });
// }
const deleteRequest = (url) => {
return new Promise((resolve, reject) => {
_axios.delete(url)
.then(
response => {
resolve(response)
},
err => {
reject(err)
}
)
})
}
/**
* put 请求方法
* @param url
* @param data
* @returns {Promise}
*/
const put = (url, params) => {
return new Promise((resolve, reject) => {
_axios.put(url, qs.stringify(params))
.then(
response => {
resolve(response)
},
err => {
reject(err)
}
)
})
}
export default {
get,
post,
deleteRequest,
put
}
2、vue.config.js
// vue.config.js
module.exports = {
//本地验证接口时用
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
runtimeCompiler: true, //是否使用包含运行时编译器的Vue内核版本
lintOnSave: false,
//publicPath: '/dist/',
//outputDir: './dist',
transpileDependencies: [
'vue-socket.io',
'vue-echarts',
'resize-detector',
],
devServer: {
open: true,
// host: 'localhost',
host: '0.0.0.0',
port: 8080,
hot: true,
disableHostCheck: true,
https: false,
//以上的ip和端口是我们本机的;下面为需要跨域的
proxy: {
//配置跨域
'/api': {
// target: 'http://10.88.155.43/takweb-legal-platform/lumen/public/rest/', //真实数据:这里后台的地址模拟的;应该填写你们真实的后台接口1
target: 'http://10.88.155.45:9910/rest/', //真实数据:这里后台的地址模拟的;应该填写你们真实的后台接口1
// target: 'http://localhost:3000/rest/', //node模拟数据:这里后台的地址模拟的;应该填写你们真实的后台接口
ws: true,
changOrigin: true, //允许跨域
pathRewrite: {
'^/api': '' //请求的时候使用这个api就可以
}
}
}
}
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//开发机验证接口时用
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// lintOnSave: false,
// runtimeCompiler: true, //是否使用包含运行时编译器的Vue内核版本
// publicPath: '/dist/',
// outputDir: './dist',
// transpileDependencies: [
// 'vue-socket.io',
// 'vue-echarts',
// 'resize-detector',
// ],
// devServer: {
// open: true,
// public: '0.0.0.0:8080',
// // // // //host: '0.0.0.0',
// // // // //port: 8080,
// hot: true,
// disableHostCheck: true,
// // // //https: false,
// // // // //以上的ip和端口是我们本机的;下面为需要跨域的
// // // // proxy: {
// // // // //配置跨域
// // // // '/api': {
// // // // target: 'http://10.88.155.43/takweb-legal-platform/lumen/public/rest/', //这里后台的地址模拟的;应该填写你们真实的后台接口
// // // // // target: 'http://localhost:3000/', //这里后台的地址模拟的;应该填写你们真实的后台接口
// // // // ws: true,
// // // // changOrigin: true, //允许跨域
// // // // pathRewrite: {
// // // // '^/api': '' //请求的时候使用这个api就可以
// // // // }
// // // // }
// // // // }
// // // // */
// }
}
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//}