闲暇之余不忘学习,提升自己 ,知识在于积累,更是一笔财富。
看完文章,感谢各位支持一下呗!
封装axios,简化操作
实现步骤
- 创建 utils/http.js 文件
- 创建 axios 实例,配置 baseURL,请求拦截器,响应拦截器
- 在 utils/index.js 中,统一导出 http
代码实现
utils/http.js
utils/index.js
import { http } from './http'
export { http }
import axios from 'axios'
const http = axios.create({
baseURL: 'http://geek.itheima.net/v1_0',
timeout: 5000
})
// 添加请求拦截器
http.interceptors.request.use((config)=> {
return config
}, (error)=> {
return Promise.reject(error)
})// 添加响应拦截器
http.interceptors.response.use((response)=> {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response
}, (error)=> {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error)
})export { http }