在 axios 请求路径只需填写资源路径:

axios.get('/adminapi/users').then(res => {
  console.log(res)
})

此时相当于向自己发送请求,会报 404。

然后在 vue.config.js 中配置反向代理:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false, /*关闭语法检查*/
  // 配置反向代理
  devServer: {
    proxy: {
      // /adminapi/* - 后台管理使用
      // /webapi/* - 企业官网使用
      '/adminapi': {
        target: 'http://localhost:3000',   // 此时后端是 3000
        changeOrigin: true,
      }
    }
  }
})

或者使用 vite.config.js :

import {fileURLToPath, URL} from 'node:url'
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
    ],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    server: {
        proxy: {
        	// 讲解:如果请求路径为 http://localhost:5173/api/xxx
        	// 1. 先换源,http://localhost:8080/api/xxx 为后端的源
        	// 2. 再重写 /api 为空,http://localhost:8080/xxx  反向代理成功
            '/api': {  // 如果请求路径含有 /api
                target: 'http://localhost:8080',  // target 将源更换为这个,此时后端是 8080
                changeOrigin: true,  // 是否改变域
                rewrite: (path) => path.replace(/^\/api/, ''),  // 将 '/api' 重写为 ''
            }
        }
    }
})

利用反向代理将请求转发出去。

在这里插入图片描述

请求成功!

当然最好还是跟着官方文档走 :代理跨域

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
// 引入svg需要用到的插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
// mock 插件提供方法
import { viteMockServe } from 'vite-plugin-mock'
// https://vitejs.dev/config/
export default defineConfig(({ command,mode }) => {
  // 获取各种环境下的对应的变量 mode模式默认为开发环境, process.cwd()为项目根目录(即index.html所在的位置)
  const env = loadEnv(mode, process.cwd())
  return {
    plugins: [vue(),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      symbolId: 'icon-[dir]-[name]',
    }),
    viteMockServe({
      localEnabled: command === 'serve',
    }),
    ],
    resolve: {
      alias: {
        "@": path.resolve("./src") // 相对路径别名配置,使用 @ 代替 src
      }
    },
    // scss 全局变量的配置
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/variable.scss";',
        },
      },
    },
    // 代理跨域
    server: {
      proxy: {
        [env.VITE_APP_BASE_API]: {
          // 获取数据的服务器地址
          target: env.VITE_APP_BASE_API,
          // 是否代理跨域
          changeOrigin: true,
          // 路径重写
          rewrite: (path) => path.replace(/^\/api/, ''),
        }
      }
    }
  }
})

env 文件见 :环境变量配置

更多推荐