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

React调用ASP.NET Core接口发起POST请求如何获取返回的新增记录ID

解答

原理说明

fetch返回的Response对象的body是流式的ReadableStream,无法直接读取结构化数据。response.json()是异步方法,会返回Promise,需要等该Promise完成后才能拿到解析后的JSON对象。你在控制台看到的Promise内部结果是浏览器的预览优化,无法直接在同步代码中取值。

实现代码

方案1:链式then写法

直接在原有代码基础上追加链式回调即可:

fetch('https://localhost:44326/api/Players/post', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    handle: data.handle,
    role: data.role,
    avatar: linkToAvatar,
  }),
})
.then(response => response.json())
.then(result => {
  // 此处result为解析完成的JSON对象
  const newPlayerId = result.id;
  console.log('新玩家ID:', newPlayerId);
  // 后续业务逻辑(如存state、跳转等)均可在此处执行
})
.catch(err => {
  // 补充错误捕获,处理请求/解析失败场景
  console.error('请求异常:', err);
});

方案2:async/await写法(更易读)

如果在React的事件函数、useEffect等场景使用,推荐用async/await语法:

// 函数前加async关键字
const createPlayer = async () => {
  try {
    const response = await fetch('https://localhost:44326/api/Players/post', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        handle: data.handle,
        role: data.role,
        avatar: linkToAvatar,
      }),
    });
    const result = await response.json();
    const newPlayerId = result.id;
    console.log('新玩家ID:', newPlayerId);
  } catch (err) {
    console.error('请求异常:', err);
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:54:04