You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React/Vite项目调用Express API遇CORS错误,求解决方案

解决Vite React + Express认证接口CORS问题

以下是针对你的问题的具体解决方案,兼顾开发和生产环境:

1. 优化Express的CORS配置

默认的cors()虽允许所有源,但生产环境需要更严谨的配置,同时确保开发环境正常访问。修改服务器主代码:

import express from 'express'
import auth from './API/auth.js'
import cors from 'cors'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'

const app = express()

// 配置CORS选项
const corsOptions = {
  // 根据环境切换允许的源
  origin: process.env.NODE_ENV === 'production' 
    ? 'https://your-production-domain.com' // 替换为你的生产域名
    : 'http://localhost:5173', // Vite默认开发端口
  credentials: true, // 允许携带凭证(如Cookie),后续认证需要
  allowedHeaders: ['Content-Type', 'Authorization']
}
app.use(cors(corsOptions))

app.use(bodyParser.json())
app.use(auth)
const port = 8000

mongoose.connect('mongodb://127.0.0.1:27017')
  .then(() => {
    console.log('Connection to MongoDB established')
  })
  .catch(err => {
    console.error('Failed to connect to Mongo', err)
  })
app.listen(port, () => {
  console.log(`Express server listening on ${port}`)
})

2. 正确配置Vite开发服务器代理

开发环境下用Vite代理绕过CORS,修改vite.config.js:

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

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      // 匹配所有以/auth开头的请求
      '/auth': {
        target: 'http://localhost:8000',
        changeOrigin: true, // 必须开启,否则后端会认为请求来自Vite服务器而非浏览器
      }
    }
  }
})

3. 调整Axios实例配置

根据环境切换baseURL,同时确保凭证配置正确:

import axios from "axios";

const instance = axios.create({
  // 开发环境用代理路径,生产环境用实际后端地址
  baseURL: import.meta.env.VITE_REACT_APP_BASE_URL || '/',
  withCredentials: true, // 和后端corsOptions的credentials对应
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  }
})

export default instance

4. 避免路由级别的CORS冲突

确保你的auth路由文件中没有手动设置Access-Control-Allow-Origin这类响应头,否则会和cors包的配置冲突,导致CORS错误。

5. 清除浏览器缓存

打开浏览器开发者工具(F12),在Network标签下勾选「Disable cache」,然后刷新页面重新发起请求,避免旧的CORS策略缓存影响。


内容的提问来源于stack exchange,提问作者Daro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:42:30