【问题标题】:How to catch an error from express proxy to React?如何捕获从快速代理到 React 的错误?
【发布时间】:2021-04-22 11:23:17
【问题描述】:

我使用 express 服务器作为我的 React 的代理,但问题是我无法在我的反应中恢复错误,无论我用户返回 next(err) 还是 res.send(err),最后一个会去然后但不会赶上。我该如何处理这个问题?

这是我的快速代理代码


axios({
      url:URL,
      method: "post",
      headers: header,
      data: body
    })
      .then(response => {

        res.send(response.data);
      })
      .catch(err => {
   
        res.send(err);
        // return next(err)
      });

这是我的 React 操作

  axios
    .post("api/", body)
    .then(response => {
      console.log( response.data)

    })
    .catch(err => {
      console.log("I want to catch the error here, but. I can't ", err);
  
    });

【问题讨论】:

    标签: javascript node.js reactjs express axios


    【解决方案1】:

    你可以得到这样的错误:err.response.data 就我而言,我从后端获得了错误属性。所以,我使用了 err.response.data.error

    我的代码:

     axios
      .get(`${API}`)
      .then(response => {
         return response.data
      })
      .then(data => {
         console.log(data)
      })
      .catch(error => {
         console.log(error.response.data.error)
      })`
    

    【讨论】:

    • 但我需要的是在 React 上显示错误......
    【解决方案2】:

    这是您在使用 axios post 时捕获错误的方式 执行 POST 请求

    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    

    如果axios.post 被调用,您的第二个 sn-p 应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 2020-03-12
      相关资源
      最近更新 更多