SoFunction
Updated on 2025-04-04

vue3+axios encapsulation interceptor method

Install axios

 yarn add axios
 npm install axios

Encapsulation request configuration interceptor

existsrc/api/encapsulate our requests.

import axios from "axios";
import {useCommonStore} from "../store/module/";
import {storeToRefs} from "pinia";

// Set the interface timeout time = 60000;
// Request address = '';

// http request interceptor(
    config =>{
        // Get token        const  commonStore = useCommonStore()
        const { token } = storeToRefs( commonStore )
        ('token',)
        // Configure the request header         = {
            // 'Content-Type':'application/x-www-form-urlencoded', // Transfer parameter form            'Content-Type': 'application/json;charset=UTF-8', // JSON            'Authorization': `Bearer ${}`, // Set Authorization            // 'token': // Or set token
        };
        return config;
    },
    error => {
        return (error);
    }
)

// http response interceptor(
    response => {
        return response;
    },
    error => {
        const { response } = error;
        if (response) {
            // Error status code            if ( === 400) {
                // Request 400            } else if ( === 401) {
                // Unauthorized, please log in again            } else if ( === 403) {
                // Access denied (403)            }
            return ();
        } else {
            ('The network connection is abnormal, please try again later!')
        }
    }
)

// Encapsulate get post requestexport function request (url,params = {},type = 'POST') {
    return new Promise((resolve,reject) => {
        let promise
        if (() === 'GET') {
            promise = axios({url,params})
        } else if (() === 'POST') {
            promise = axios({
                method: 'POST',
                url,
                data: params
            })
        }

        ( res => {
            resolve(res)
        }).catch (err => {
            reject(err)
        })
    })
}

Api unified management

existsrc/api/Unified management of our interface API in files

// Introduce requestimport { request } from "./"

// Modular interfaceexport class UserApi {
    static async login(params) {
        return request('/login',params,'post')
    }
    static async register(params) {
        return request('/register',params,'post')
    }
    static async getUserInfo(params) {
        return request('/userInfo',params,'get')
    }
}

export class BookApi {
    static async getBookList(params) {
        return request('/bookList',params,'get')
    }
}

application

<script setup>
import {UserApi} from "../api/";
const login = async () => {
  const params = {
    username: 'admin',
    password: '123456',
  }
  const res = await (params)
}
</script>

Cross-domain issues

existConfiguration.

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path";

// /config/
export default defineConfig({
  plugins: [vue()],
  server: {
    host: '127.0.0.1',
    port: 3000,
    proxy: {
      '/api': {
        target: '', // Actual request address        changeOrigin: true,
        rewrite: (path) =&gt; (/^\/api/, '')
      }
    }
  },
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.