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

React/Node场景下如何确保POST请求完成后再发起GET请求

问题根因

你现有的postReq方法没有返回axios POST请求产生的Promise对象,await this.postReq()实际等待的是同步返回的字符串"Finished"或者数字1,不会等待异步POST请求执行完毕,因此GET请求会提前触发。

修复方案

第一步:修改postReq方法,统一返回Promise

postReq = () => {
  if(this.state.theUrl.length > 0) {
    // 返回axios请求的Promise对象,让外层await可以等待请求完成
    return axios.post('http://localhost:5000/check', {
      url: this.state.theUrl
    }).then(function(response) {
      console.log("Success")
    }).catch(function(error) {
      console.log(error)
      // 抛出错误方便上层捕获
      throw error
    });
  }
  else {
    // 无请求场景返回已resolve的Promise,保持返回类型统一
    return Promise.resolve(1);
  }
}

第二步:优化callApi方法,增加异常处理

callApi = async() => {
  try {
    await this.postReq();
    // 确认POST执行完成后再触发GET请求
    await this.getReq();
  } catch (err) {
    console.error('流程执行出错:', err)
  }
}
可选优化方案

你当前的业务逻辑只需要POST发送文本、拿到处理后的结果,完全可以让Node端的POST接口直接把修改后的文本放在响应体中返回,不需要额外发起GET请求,既简化代码又减少网络开销:

// 简化后的单请求实现
postReq = async () => {
  if(this.state.theUrl.length <= 0) return
  try {
    const postRes = await axios.post('http://localhost:5000/check', {
      url: this.state.theUrl
    })
    // 直接拿POST返回的处理结果更新状态,不需要额外GET
    this.setState({summaryParts: postRes.data, postResponse: ""})
  } catch (err) {
    console.log(err)
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:00:00