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

相关推荐
yuanyxh7 小时前
Mac 软件推荐
前端·javascript·程序员
万少7 小时前
AtomCode开发微信小程序《谁去呀》 全流程
前端·javascript·后端
某人辛木7 小时前
Web自动化测试
前端·python·pycharm·pytest
Kagol8 小时前
Superpowers GSD gstack AgentSkills深度测评
前端·人工智能
excel9 小时前
JavaScript 字符串与模板字面量:从表象到本质理解
前端
京东云开发者9 小时前
当AI成为导演-如何用AI创作动漫短剧
前端
李白的天不白10 小时前
使用 SmartAdmin 进行前后端开发
java·前端
乘风gg10 小时前
🤡PUA AI Coding 工具 的 10 条终极语录
前端·ai编程·claude
学Linux的语莫10 小时前
Vue 3 入门教程
前端·javascript·vue.js
怕浪猫10 小时前
第一章、Chrome DevTools Protocol (CDP) 详解
前端·javascript·chrome