Vue-cli 请求代理配置及封装 Axios
大佬止步,小白往下。
HTTP 请求代理配置
vue-cli 2.x
// /config/index.js
proxyTable: {
'/api-1': {
target: 'http://xxx.xxx.xxx.xxx:8080',
changeOrigin: true,
pathRewrite: {
// 以 /api-1 开头的请求路径都会被 'http://xxx.xxx.xxx.xxx:8080' 代理
'^/api-1': ''
}
},
'/api-2': {
target: 'http://xxx.xxx.xxx.xxx:8081',
changeOrigin: true,
pathRewrite: {
// 以 /api-2 开头的请求路径都会被 'http://xxx.xxx.xxx.xxx:8081' 代理
'^/api-2': ''
}
}
}
vue-cli 3.x
// vue.config.js(该文件在项目的根目录下,默认没有这个文件,用时需要自己新建)
module.exports = {
devServer: {
proxy: {
'/api-1': {
target: 'http://xxx.xxx.xxx.xxx:8080',
ws: true, // 是否开启 websokets
secure: false, // 是否安全,https 为 true,http 为 false
changeOrigin: true,
pathRewrite: {
'^/api-1': ''
}
},
'/api-2': {
target: 'http://xxx.xxx.xxx.xxx:8081',
ws: true,
secure: false,
changeOrigin: true,
pathRewrite: {
'^/api-2': ''
}
}
}
}
};
调用
axios({
// xxxx/xxxx 为代理配置的 target 后的路径
url: '/api-1/xxxx/xxxx',
...
});
Axios 封装
封装请求共用函数
变换较大的、常用的参数放前面,不常改变的参数和有默认值的参数放在参数队列最后。
// /src/api/ajax.js (该目录及名称可自定义)
import axios from 'axios'
const request = axios.create({
// 生产环境和开发环境的请求域名和端口
baseURL: process.env.NODE_ENV === 'production' ? 'http://192.168.0.247:92/' : '',
withCredentials: false
});
request.interceptors.request.use(config => {
// 请求拦截器,可在此做请求之前的处理,比如绑定 token,存储或清除某些数据等
return config;
});
request.interceptors.response.use(res => {
// 响应拦截器,可在此处做统一的请求失败处理等操作
console.log(res);
});
export default function ajax(
url,
params = {},
type = 'post',
errorCallBack,
header = {headers: {'Content-Type': 'application/json'}}
) {
return new Promise(resolve => {
request[type](url, type === 'get' ? {params} : params, header)
.then(res => resolve(res.data))
.catch(e => {
errorCallBack && errorCallBack();
console.log(e);
});
});
}
封装项目中的请求列表列表
// /src/api/index.js (该目录及名称可自定义)
import ajax from "./ajax";
const API1 = '/api-1';
const API2 = '/api-2';
// params 是个对象,存放请求所有参数列表
const req1 = params => ajax(API1 + '/xxx/xxx/xxx', params);
const req2 = params => ajax(API2 + '/xxx/xxx/xxx', params);
export default {
req1,
req2
}
在 main.js 配置
// main.js
...
import $http from './api'
Vue.prototype.$http = $http;
...
在任意组件中的调用
export default {
name: 'xxx',
methods: {
async req() {
// res为请求返回值,如果要传其他值,看上面封装的 ajax 函数的参数列表
const res = await this.$http.req1({
... // 参数列表
});
}
}
}