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博客

相关推荐
倾颜3 小时前
从 textarea 到 AI 输入框:用 Tiptap 实现 / 命令、@ 引用和结构化请求
前端·langchain·next.js
kyriewen4 小时前
程序员连夜带团队跑路,省了23万:这AI太贵,真的用不起了
前端·javascript·openai
kyriewen5 小时前
你写的代码没有测试,就像出门不锁门——Jest + Testing Library 从入门到不慌
前端·单元测试·jest
yuzhiboyouye5 小时前
web前端英语面试
前端·面试·状态模式
canonical_entropy6 小时前
下一代低代码渲染框架 nop-chaos-flux 的设计原则
前端·低代码·前端框架
东方小月7 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构
我叫黑大帅7 小时前
为什么需要 @types/react?解决“无法找到模块 react 的声明文件”报错
前端·javascript·面试
之歆7 小时前
DAY_21JavaScript 深度解析:数组(Array)与函数(Function)(一)
前端·javascript
XinZong8 小时前
【AI社交】基于OpenClaw自研轻量化AI社交平台实战
前端
Le_ee8 小时前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php