使用vite解决跨域

直接看vite.config.ts配置

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],

  server: {
    open: true, // 是否自动打开浏览器
    port: 3000, // 端口号

    // 代理解决跨域
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:8000',  // 接口源地址
        changeOrigin: true,   // 开启跨域
        rewrite: (path => path.replace('/^\/api/', ''))
      }
    }
  }
});

然后看前端接口请求方式,不需要带域名

const response = await fetch("/api/user/1");
const text = await response.text();

参考文章:
1、10 种跨域解决方案(附终极方案)
2、什么是跨域,怎么解决跨域?

posted @ 2023-07-03 23:37  白日何短短  阅读(1317)  评论(0编辑  收藏  举报