使用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 @   白日何短短  阅读(1597)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示