Vue项目使用axios配置请求拦截和响应拦截以及判断请求超时处理提示

哈喽大家好啊,最近做Vue项目看到axios

axios官网:起步 | Axios 中文文档 | Axios 中文网 (axios-http.cn)​​​​​​

重要点:

axios是基于Promise封装的

axios能拦截请求和响应

axios能自动转换成json数据

等等

安装:

$ npm install axios

Vue项目中使用axios实现请求拦截

javascript 复制代码
import axios from 'axios';// 引入axios

const httpAxios = axios.create({});// 创建实例

let config = {
	TIMEOUT: 600000,//设置超时时间为10min
};

// axios 配置超时时间
httpAxios.defaults.timeout = config.TIMEOUT;
  
  // axios设置  请求拦截
  httpAxios.interceptors.request.use(
    // config配置选项
    config => {
      console.log(config,'1')
      return config;
    },
    // error
    error => {
      return Promise.reject(error);
    }
  )

Vue项目中使用axios实现响应拦截

javascript 复制代码
 // axios响应拦截
  httpAxios.interceptors.response.use(
    // response响应成功
    response => {
      const config = response.config;
      console.log(config,'2')
      return response;
    },
    // 响应error
    error => {
      const config = error.config;
      console.log(config,'3')
      if(error.message.includes('timeout')) {
        return Promise.reject('timeout');// reject这个错误信息
        // 判断请求异常信息中是否含有超时timeout字符串
      }
      return Promise.reject('网络链接失败,请稍后再试!')
    }
  )

封装axios请求

javascript 复制代码
export const getHttpInfo = function (data) {
  return new Promise((resolve, reject) => {
    let token = ''
    if (data.headers) {
      token = data.headers.Authorization
    }
    httpAxios(data).then((res) => {
      resolve(res)
    }).catch((e) => {})
  })
}

设置超时时间并在响应拦截中判断超时并提示

javascript 复制代码
 gethttpInfo({
          method: 'post',
          url: url,
          data: this.order,
          headers: {
            'Authorization': localStorage.getItem('token')
          }
        }).then((res) => {
            }).catch((error) => {
              this.$message({
                type: 'warning',
                message: error!=='timeout' ? error : '其他错误'
          })
        });

参考原文:

Vue项目请求超时处理_vue接口请求超时处理_一捆铁树枝的博客-CSDN博客

相关推荐
寂寞狼牙冷4 分钟前
封装fetch替换axios
前端
用户4611696572820 分钟前
网站 HTTPS 不稳定?证书排查指南
前端
n876531 分钟前
Playwright Java WEB UI 自动化实现框架与逻辑
java·前端·ui
keyipatience33 分钟前
TypeScript学习(1)
前端·javascript·学习·typescript·html·css3
xifangge20251 小时前
基于 JavaScript 实现 CNC 数控切削参数与螺纹公差纯前端核算引擎
开发语言·前端·javascript
wangruofeng1 小时前
2026 Web 技术选型指南,AI 时代如何选择适合项目的技术栈
前端·aigc·ai编程
honkun62 小时前
vue 表格组件 vxe-table 修改滚动条样式,修改滚动条样式,统一宽度、颜色与自动隐藏
前端·javascript·vue.js
爱勇宝2 小时前
研究数字孪生的这半年,做了个 Demo,也有了一些新想法
前端·程序员
不可能片场2 小时前
工程实践 一个缓存把选片从十分钟压到一分钟
前端·electron
前端小万2 小时前
探索副业五个月,最终以放弃告终
前端·后端·面试