react\vue 等框架使用axios,自定义封装requset异步请求
前端不管用那种框架,其中异步请求都可以使用axios插件进行封装,于此整理通用方法。并赋使用方法,
1、以vue为例封装,react同理 此处封装的文件为 globle.vue
import axios from 'axios' import Vue from 'vue' import store from '@/store/index' // 自定义vuex store // 后台接口地址const baseUrl = 'http://dev.xxx.cnpc.com.cn:8080/' // url 地址 const request = axios.create({ // baseURL: baseUrl, headers: { 'Content-Type': 'application/json;' }, data: {}, timeout: 30000, changeOrigin: true, // 允许跨域 credentials: 'include', withCredentials: true }) // http request 请求拦截器 request.interceptors.request.use( config => { // 增加判断,除登陆接口外,添加token; 此处判断需根据自身项目实际情况进行自定义 if (config.url.indexOf('account/login') !== 0) { config.headers['HRSHTOKEN'] = sessionStorage.getItem('token') } // config.data = `${JSON.stringify(config.data)}` return config }, err => { console.log('加载超时') return Promise.reject(err) }) // http response 返回拦截器 request.interceptors.response.use( response => {
// 此处判断依旧根据项目自身情况进行自定义; 此处判断返回status状态为200时表示成功,else进行弹框提示message if (response.data.status === '200') { return response } else { Vue.$vux.toast.show({ text: response.data.message, type: 'text', width: '50%' }) return Promise.reject(new Error(response.data.message)) // 拦截打印错误信息,在调用时,必须加入catch,浏览器才不会显示红色报错 } }, error => { // 请求失败时的提示 console.log(error.response.status) return Promise.reject(error) })
export default {
request
}
2、vue项目的 main.js 进行全局注册,方便调取使用
import _global from '@/global/global' // 全局注册组件 Vue.prototype.GLOBAL = _global
3、模块文件直接调用, 在模块中进行response 数据处理
const _this = this this.GLOBAL.request.post('tax/taxInfo', reqData).then(({data}) => { _this.list = data.payload.list }).catch(e => { // 这里必须加入catch不然控制台 error message 显示为红色错误提示 console.log(e) })
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构