跨域代理

74 阅读1分钟

跨域代理

# vite.config.ts
import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// 引入viteMockServe 
export default defineConfig({
  plugins: [vue(), vueJsx() 
   ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server:{
    proxy: { // 本地开发环境通过代理实现跨域,生产环境使用 nginx 转发
      // 正则表达式写法
      '^/api': {
        target: 'http://localhost:5173/', // 后端服务实际地址
        changeOrigin: true, //开启代理
        rewrite: (path) => path.replace(/^\/api/, '')
      },
      '^/bpi': {
        target: 'https://www.maoyan.com/', // 后端服务实际地址
        changeOrigin: true, //开启代理
        rewrite: (path) => path.replace(/^\/bpi/, '')
      }
    }
  }
})