Axios 'GET' 请求未决,但从未到达服务器

Axios 'GET' request is pending but it never reaches the server

我在我的 React 应用程序上使用 axios 从我的服务器(节点)获取数据。我的 GET 请求在 chrome 开发人员工具中处于待处理状态,如果我在提供的路径上刷新应用程序(例如 http://localhost:3000/category/5d68936732d1180004e516cb),则不会到达服务器。但是,如果我从主页重定向,它会起作用。

我尝试了不同的变体来确保我在服务器端结束响应。

有几个帖子有相关问题(例如,request not reaching the server, POST request does not reach the server),但不幸的是对我的情况没有帮助。

这是我在 React 应用程序中的主要调用:

  componentDidMount() {
    console.log('I am here!'); // this gets executed even on page refresh
    axios.get(`/api/categories/${this.props.id}`)
      .then( (res) => {
        this.setState({
          title: res.data.category.title,
          module: res.data.category.module ? true : false,
          ...res.data
        })
      }, (err) => console.log(err))
      .catch(err => console.log(err));
  }

在我的后端,我在通过用户验证后调用了这个函数:

module.exports.publishedCategories = async function(req, res) {
  try {    
    // some code that I removed for clarity
    res.json({
      category,
      children,
      flagged: flaggedCategories
    });
  } catch(err) {
       console.log(err);
       res.sendStatus(500).end();
    }
}

关于我的路由的更多代码:

index.js

<Route
    path='/category/:id'
    render={ (props) => {
       return <Category id={props.match.params.id} />
    }}
/>

我没有收到任何错误消息...

我对切换到 componentDidUpdate() 的最初解决方案过于热心。这仅适用于页面刷新但不适用于重定向(即,我遇到了相反的问题)。我最终的解决方案如下:

  componentDidMount = async () => {
    setTimeout( async () => {
      this.loadCategory();
    }, 10)
  }

  componentDidUpdate = async (props, state) => {
    if(props.match.params.id !== this.props.match.params.id) {
      this.loadCategory();
      return;
    }
    return false;
  }

  loadCategory = async () => {
    let result = await axios.get(`/api/categories/${this.props.match.params.id}`);
    this.setState({
      title: result.data.category.title,
      module: result.data.category.module ? true : false,
      ...result.data
    });
  }

我不确定为什么添加 setTimeout() 对 componentDidMount() 有效。

根据文档 componentDidUpdate(),这对 netork 更新很有用,但是您需要将之前的 props 与当前的 props 进行比较。

不幸的是,我不确定如何绕过 setTimeout() hack,但它似乎有效。