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

React调用C# ASP.NET Core接口返回空数组问题求助

问题排查与修复方案

1. 修正Axios响应数据获取逻辑

你的代码误用了response.json,这是原生fetch API的用法,而Axios会自动解析JSON响应,正确的数据存储在response.data字段中。错误的取值会导致data被设置为undefined,进而触发map时的报错。

修改这行代码:

.then(response => setData(response.json))

改为:

.then(response => setData(response.data))

2. 解决异步状态更新的日志问题

setState是异步操作,你当前的console.log(data)会输出初始的空数组,无法看到接口返回的真实数据。如果需要调试,要么把日志放在then回调内,要么新增一个监听data变化的useEffect:

// 方式1:在then内打印真实返回数据
.then(response => {
  setData(response.data);
  console.log(response.data);
})

// 方式2:新增useEffect监听data变化
useEffect(() => {
  console.log('数据更新:', data);
}, [data]);

3. 配置后端CORS跨域支持

React项目默认运行在localhost:3000,而后端在localhost:5029,属于跨域请求,ASP.NET Core后端必须配置CORS允许前端域名访问:

在后端Program.cs中添加以下配置:

// 注册CORS服务
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowReactApp",
        policy => policy.WithOrigins("http://localhost:3000") // React项目地址
                        .AllowAnyHeader()
                        .AllowAnyMethod());
});

// 在UseRouting之后、UseAuthorization之前启用CORS
app.UseCors("AllowReactApp");

4. 完善错误处理逻辑

当前的try/catch无法捕获Axios的异步错误,因为axios.get返回的是Promise,需要通过.catch()捕获,或者改用async/await语法:

方式1:Promise链式调用加catch

axios.get('http://localhost:5029/api/Works')
  .then(response => setData(response.data))
  .catch(error => {
    console.error('请求失败:', error);
    alert("error");
  });

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

useEffect(() => {
  const fetchData = async () => {
    try {
      const response = await axios.get('http://localhost:5029/api/Works');
      setData(response.data);
    } catch (error) {
      console.error('请求出错:', error);
      alert("error");
    }
  };
  fetchData();
}, []);

修改后的完整React代码

import { useState, useEffect } from 'react';
import axios from 'axios';

export default function Get() {
    const [data, setData] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await axios.get('http://localhost:5029/api/Works');
                setData(response.data);
                console.log('接口返回数据:', response.data);
            } catch (error) {
                console.error('请求出错:', error);
                alert("error");
            }
        };
        fetchData();
    }, []);

    // 监听data变化打印日志
    useEffect(() => {
        console.log('当前状态数据:', data);
    }, [data]);

    return (
        <>
            {data.map((item, index) => (
                <p key={index}>{JSON.stringify(item)}</p> {/* 如果是对象,转成字符串避免显示[object Object] */}
            ))}
        </>
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:45:20