为什么二次封装?
请求拦截器,响应拦截器,请求拦截器,可以再请求发送之前处理一些业务,响应拦截器,当侮辱器数据返回后,可以处理一些
import axios from "axios"
export default axios;
const request = axios.create({
baseURL: "/api",
timeout: 5000
})
request.interceptors.request.use((config) => {
return config;
})
request.interceptors.response.use((res) => {
return res.data;
}, (error) => {
return Promise.reject(new Error("false"));
})
发送请求
import requests from './request'
export const reqCategoryList = () => {
return requests({
url: "api/product/getBaseCategoryList",
method: 'get'
})
}
解决跨域问题: vue.config.js文件中配置代理
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false,
devServer: {
proxy: {
"api": {
target: "http://39.98.123.211",
}
}
}
})
案例比如要使用进度条,在请求之前开始,请求成功后停止
import axios from "axios"
export default axios;
import nprogress from "nprogress";
import "nprogress/nprogress.css"
const request = axios.create({
baseURL: "/api",
timeout: 5000
})
request.interceptors.request.use((config) => {
nprogress.start()
return config;
})
request.interceptors.response.use((res) => {
nprogress.done()
return res.data;
}, (error) => {
return Promise.reject(new Error("false"));
})
总结一下,二次封装后可以再请求发送前和请求发送后做一些处理不如过滤,或者执行一些业务逻辑。
|