axios使用流程
1.可以dependencies安装:npm install axios
"axios": "^0.21.1",
注意版本最好0.21.1,不然会提示安全隐患。官网安装axios到生产依赖,其实安装到开发依赖也没问题,打包一样会打进去。
2.创建request文件src/utils/request.js(路径和名字依据自己喜好):
import axios from "axios";
const _axios = axios.create({
baseURL: "/api",
// withCredentials: true, //表示跨域请求时是否需要使用凭证,缺省值为false
timeout: 10000,
headers: {
"Cache-Control": "no-cache"
},
});
// 添加请求拦截器
_axios.interceptors.request.use(
function(config) {
// 在发送请求之前做些什么
if (config.headers['Cache-Control'] === 'no-cache') {
config.params = Object.assign(config.params || {}, {t: Date.now()});
}
return config;
},
function(error) {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
_axios.interceptors.response.use(
function(res) {
// 对响应数据做点什么
return res;
},
function(error) {
// 对响应错误做点什么
return Promise.reject(error);
}
);
export default _axios;
这个例子引入axios包,实例化,最后导出一个axios实例。配置了基本的baseURL、超时时间、get请求不适用浏览器缓存(其实就是请求url后面加个时间戳查询参数),此外拦截器里面基本没做什么事情。
3.你存放接口的文件中导入axios实例并使用:
import request from "./../utils/request";
export function requestUserInfo() {
return request({
url: `/users/ruanyf`,
params: {
wrkCd: "test-wrkCd",
page: "test-page",
size: "test-size",
},
})
.then((res) => {
return Promise.resolve(res);
})
.catch((error) => {
return Promise.reject(error);
});
}
默认请求地址是本机地址+实例baseURL+接口url,测试环境接口如果没部署在本机,测试环境需要配置代理。
4.vue.config.js配置代理
module.exports = {
devServer: {
open: false,
proxy: {
'/api': {
// 注意:浏览器Network/Headers/General/RequestURL依然是:http://localhost:8080/api/users/ruanyf
// 实际请求地址为:https://api.github.com/users/ruanyf
target: 'https://api.github.com/',// 要访问的跨域的域名
ws: true,
secure: true, // 使用的是http协议则设置为false,https协议则设置为true
changOrigin: true, // 开启代理
// 相当于请求遇见 /api 才做代理,但真实的请求中没有/api,所以在pathRewrite中把 /api 去掉, 这样既有了标识, 又能在请求接口中把 /api 去掉。
// pathRewrite:如果不写则只能修改代理的域名,如果写则可以修改代理的域名和后边的路径。
pathRewrite: {
'^/api': ''
}
}
}
},
};
感谢阮老师,我是阮老师的小迷弟。
工欲善其事 必先利其器

浙公网安备 33010602011771号