首页 > 其他分享 >vue3封装axios并使用拦截器处理错误

vue3封装axios并使用拦截器处理错误

时间:2022-12-28 17:13:34浏览次数:43  
标签:function axios http 拦截器 vue3 return message response

utils/http.js

import axios from "axios";

const http = axios.create({
  withCredentials: false,
  timeout: 30000,
  baseURL: "http://127.0.0.1:8000",
  headers: {
    Accept: "application/json",
  },
});

http.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    const message = error.message || {};
    if (message) alert(message);
    return Promise.reject(message);
  }
);

export default http;

 使用

<script setup>
import http from "../utils/http.js";
http.get("/login").then(function (response) {
  console.log(response);
});
</script>
<template>
  <div class="about">
    <h1>This is home page</h1>
  </div>
</template>

 

标签:function,axios,http,拦截器,vue3,return,message,response
From: https://www.cnblogs.com/caroline2016/p/17010570.html

相关文章

  • Vue3 富文本编辑器
    官网https://www.wangeditor.com/v5/for-frame.html#%E4%BD%BF%E7%94%A8-1 安装:npminstall@wangeditor/editor--savenpminstall@wangeditor/editor-for-vue@n......
  • vue3使用sweetalert2替代默认的alert/confirm框
    安装#运行时依赖package.json的dependenciesnpminstallsweetalert2--save#开发时依赖package.json的devDependenciesnpminstallsweetalert2--save-dev ......
  • vue3使用bootstrap的简单加载遮罩层
    之前有使用过bootstrap做过一个简单的加载遮罩层,现把它加入到vue中。加载遮罩层一般来讲整个app共用一个就可以,因此放到App.vue中,为不影响其它的业务逻辑,放到</template>......
  • vue3使用vue-router构建SPA
    使用自动化构建工具vite搭建新项目#某个目录下执行npmcreatevite@latest 按照提示初始化项目,并按照提示:cdvite-projectnpminstallnpmrundev生成目录结构......
  • Vue3源码阅读梳理
    简单代码例子const{createApp,defineComponent,computed,watch,ref,reactive,effect}=Vueconstapp=createApp({components:[],template:`<div......
  • Vue3+vant+ts 上滑加载,解决上滑调用多次数据的问题
    之前用vue2的时候,写过vue2的用法,链接在这里点击跳转哈,用得挺好的,也没啥问题,照葫芦画瓢的做出来了,但是有问题,下滑之后调用多次数据,按理说组件通过 loading 和 finished......
  • Vue3 Composition API 的优势
     1.OptionsAPI存在的问题使用传统OptionsAPI中,新增或者修改一个需求,就需要分别在data,methods,computed里修改。 2.CompositionAPI的优势我们可以更加优雅的组织......
  • Vue3之provide 与 inject
     provide与inject 作用:实现祖与后代组件间通信,儿子组件中也能用这种方式,但是一般不这么用,父子组件传信息一般直接用props属性。套路:父组件有一个 provide 选项......
  • Vue3之响应式数据的判断
    响应式数据的判断isRef:检查一个值是否为一个ref对象isReactive:检查一个对象是否是由 reactive 创建的响应式代理isReadonly:检查一个对象是否是由 readonly......
  • Vue3之customRef
    customRef作用:创建一个自定义的ref,并对其依赖项跟踪和更新触发进行显式控制。比如在input更新数据之后,设置指定时间之后再在h3标签上重新展示最新的数据:<templ......