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

React调用Express开发的REST API获取数据失败,遇CORS问题

解决React调用Express API的CORS跨域问题

问题根源

你的React项目运行在http://localhost:5173,Express API部署在http://localhost:3000,属于不同端口的跨域请求。浏览器的同源策略(CORS)会拦截这类请求,因为Express返回的响应中缺少Access-Control-Allow-Origin头。

另外注意:你代码里的try/catch写法无效——Promise的异步错误无法被同步的try/catch捕获,错误不会进入你的catch块。

解决方案

方法1:在Express项目中启用CORS中间件

这是最直接的解决方式:

  1. 安装cors依赖:
npm install cors
  1. 在Express入口文件(如app.js/server.js)中引入并配置:
const express = require('express');
const cors = require('cors');
const app = express();

// 开发环境允许所有来源(生产环境建议指定具体域名)
app.use(cors());

// 生产环境可指定允许的单一来源,更安全
// app.use(cors({
//   origin: 'http://localhost:5173'
// }));

// 挂载你的API路由
app.use('/api/admin', yourAdminRouter);

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

方法2:在React项目中配置代理(无需修改Express)

如果你用Vite搭建React项目(5173是Vite默认端口),可以通过代理绕开CORS:

  1. 在项目根目录创建/修改vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true
      }
    }
  }
})
  1. 修改API请求路径,把http://localhost:3000/api/admin改为/api/admin,请求会被Vite自动代理到Express服务器。

修复错误捕获逻辑

原代码的错误捕获无效,需修改为以下两种方式之一:

方式1:Promise链式调用

React.useEffect(() => {
  dispatchVenues({ type: "FETCH_INIT" });
  VenueDataService.listAllVenues()
    .then((result) => {
      dispatchVenues({
        type: "FETCH_SUCCESS",
        payload: result.data,
      });
    })
    .catch(error => {
      dispatchVenues({ type: "FETCH_FAILURE" });
      console.log(error);
    });
}, []);

方式2:async/await结合try/catch

React.useEffect(() => {
  const fetchVenues = async () => {
    dispatchVenues({ type: "FETCH_INIT" });
    try {
      const result = await VenueDataService.listAllVenues();
      dispatchVenues({
        type: "FETCH_SUCCESS",
        payload: result.data,
      });
    } catch(error) {
      dispatchVenues({ type: "FETCH_FAILURE" });
      console.log(error);
    }
  };
  fetchVenues();
}, []);

内容的提问来源于stack exchange,提问作者Oula R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 01:32:08