SoFunction
Updated on 2025-04-07

vue3(vite) Set proxy encapsulation axios api decoupling function

1. Set up a proxy

Open the file in the root directory and set the proxy

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
 
// /config/
export default defineConfig({
  plugins: [vue()],
  // Set up a proxy  server: {
    proxy: {
      '/api': 'xxx'
    }
  }
})

2. Axios packaging

Download axios first

npm install axios -S

Create new utils/ in the root directory and simply encapsulate axios

import axios from 'axios';
 
//1. Create an axios objectconst service = ();
 
//2. Request an interceptor(config => {
  return config;
}, error => {
  (error);
});
 
//3. Response Interceptor(response => {
  //Judge code code  return ;
},error => {
  return (error);
});
 
export default service;

3. API file

Create folders in utils folder API create file

import request from './request'
 
export function Fun( data ){
	return request({
		url:'xxx',
		method:"post",
		data
	})
}

4. Install the unplugin-auto-import plugin (vite version)

npm i unplugin-auto-import -D

Configure unplugin-auto-import while opening

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
 
//Introduce unplugin-auto-import/vite pluginimport AutoImport from 'unplugin-auto-import/vite'
 
// /config/
export default defineConfig({
  plugins: [vue(),
  AutoImport({
    imports: ['vue', 'vue-router']//Automatically import vue and vue-router related functions  })
  ],
  // Set up a proxy  server: {
    proxy: {
      '/api': ''
    }
  }
})

This is the article about vue3 (vite) setting proxy encapsulation Axios API decoupling. For more related vue3 vite setting proxy content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!