若依前后端分离项目中的vue.config.js配置
vue使用axios调用接口地址,配置一个服务端的代理,隐藏真实请求地址
1、vue.config.js配置
devServer: {
open: true,
port: port,
overlay: {
// 在浏览器不显示编译的警告
warnings: false,
// 在浏览器上显示编译的错误
errors: true
},
proxy: {
[process.env.VUE_APP_BASE_API]: {// 使用环境变量中的值
target: 'http://localhost:8790/’, //服务端接口地址
changeOrigin: true,
pathRewrite: { // 重写真实请求地址
['^' + process.env.VUE_APP_BASE_API]: '/'
}
}
}
}
2、在.env.development中配置VUE_APP_BASE_API
VUE_APP_BASE_API = '/api/'
注意:必须使用VUE_APP开头的环境变量名称,否则读取不到
3、request.js配置
import axios from 'axios'
// 创建一个 axios 实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
timeout: 10000 // request timeout
})
// request interceptor请求拦截器
service.interceptors.request.use(
config => {
// do something before request is sent 在发出请求前
console.log(config)
return config
},
error => {
// do something with request error 处理请求错误
return Promise.reject(error)
}
)
// response interceptor 响应拦截器
service.interceptors.response.use(
response => {
// 返回值 是失败的
if (response.data.isSuccess !== true) {
if (res.data.code === -1) { // 错误码是-1 时
return retryNotErrReq(res.config)
} else {
handleError(res.data.code, res.data.msg)
return Promise.reject(new Error(res.data.msg || 'Error'))
}
} else {
return res
}
},
error => {
return Promise.reject(error)
}
)
export default service
4、api.js配置
import request from './request'
export function testMessage() {
return request({
url: '/boardPush/testMessage',
method: 'post'
})
}
5、使用
testMessage().then(msg => {
console.log(msg)
})
6、总结
请求地址:
http://localhost:8082/api/boardPush/testMessage
真实请求地址:
http://localhost:8790/boardPush/testMessage
其中将
http://localhost:8082/api/
转换成了http://localhost:8790/api/
,并且重写了url地址
,将其中的/api/
替换成了/
得到了真实的请求地址