引入依赖
npm install axios
在main.js中全局引入
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'const app = createApp(App)// 全局引入axios
app.config.globalProperties.$axios = axiosapp.mount('#app')
修改vite.config.js的代理配置
import { fileURLToPath, URL } from 'node:url'import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'export default defineConfig({plugins: [vue(),],resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}},// 配置前端服务地址和端口server: {host: '0.0.0.0',// 端口port: 8991,// 是否开启 httpshttps: false,// 设置反向代理,跨域proxy: {'/api': {// 后台地址target: 'https://XXXXXXXXXXXX.com',changeOrigin: true,rewrite: path => path.replace(/^\/api/, '') // 重定向删除'/api'}}}
})
在vue中测试接口
this.$axios.post('/api/login').then(res => {console.log(res.data)}).catch(err => {console.log(err)})