vue3配置代理跨域

358 阅读1分钟

1:如果你使用 Vue CLI 进行开发,可以配置 vue.config.js 来代理请求:

// vue.config.js
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:9080',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
};

1-1:然后,你可以在前端代码中使用 /api 前缀来访问后端接口,例如:

axios.get('/api/xxl-job-admin/jobinfo/pageList?jobGroup=11&triggerStatus=0').then(response => {
  console.log(response.data);
});

这样配置后,所有以 /api 开头的请求都会被代理到 http://localhost:9080,而不会受到浏览器的跨域限制影响,最终的请求是http://localhost:9080/xxl-job-admin/jobinfo/pageList?jobGroup=11&triggerStatus=0

2:如果你在 Vite 项目中使用 vite.config.js 进行配置,可以通过以下方式配置代理来解决跨域问题:

// vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:9080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '') // 可选的重写规则
      }
    }
  }
});

  • proxy 对象定义了代理规则。
  • /api 表示所有以 /api 开头的请求都会被代理到 http://localhost:9080
  • changeOrigin: true 用于确保请求头中的 Host 值是目标 URL 的值,而不是发起请求的页面的值。
  • rewrite 可选地定义重写规则,将前缀 /api 从请求路径中移除,以适应后端接口的实际路径格式。

2-1:然后,你可以在前端代码中使用 /api 前缀来访问后端接口,例如

axios.get('/api/xxl-job-admin/jobinfo/pageList?jobGroup=11&triggerStatus=0').then(response => {
  console.log(response.data);
});

这样配置后,Vite 会在开发过程中代理所有 /api 开头的请求到指定的后端服务器,避免了浏览器的跨域问题。

记得根据你的实际情况调整 target 的值和可能需要的其他配置选项,比如安全性和性能优化