【问题标题】:How to check states after sending request in server?在服务器中发送请求后如何检查状态?
【发布时间】:2021-11-14 07:38:00
【问题描述】:

我正在尝试使用 axios 向服务器发送请求后检查状态。我设计了一个服务器,如果你提交一个空输入的表单,你会得到一个错误。如果您可以在代码中看到,我已尝试检查 finally 块中的状态,但它无法正常工作。就像我最初提交表单时没有输入一样,控制台日志显示no errors,当我尝试提交带有输入的表单时,它不会在控制台中显示任何内容。我只想检查请求中是否有error,因为我想在它们之间运行一个函数。

我使用的服务器正在运行,您可以通过将 URL 更改为 /getUser 来获取数据/提交的表单

此处代码:https://codesandbox.io/s/quizzical-danny-dv1l7?file=/src/App.js

【问题讨论】:

    标签: node.js reactjs async-await axios


    【解决方案1】:

    不是这样的。

    const [error, setError] = useState("");
    
    

    error 是初始值(空字符串)。不知道 useState 是如何工作的,但是error 是一个字符串,所以它是一个值,而不是一个引用。此变量无法在 finaly 块中更新。

    【讨论】:

    • 您知道如何实现它吗?谢谢
    【解决方案2】:

    简单的答案是您在函数内设置状态,然后尝试将其读取为您的“当前状态”。试试这个吧……

      const handleSubmit = async (e) => {
        e.preventDefault();
    
        try {
          await axios.post("https://testing-name-app.herokuapp.com/create", {
            first,
            last
          });
        } catch (error) {
          console.log("error found");
         return setError(error.response.data.errorMessage);
        } 
        // be CAREFUL with this pattern! This just means the request came back
        // with no errors, but there may be a message from your call that 
        // contained an error from your db/server etc  
        return console.log("no errors");
      };
    

    还有一种方法可以快速查看通话中发生的情况...

      const handleSubmit = async (e) => {
        e.preventDefault();
    
        let res
        try {
          res = await axios.post("https://testing-name-app.herokuapp.com/create", {
            first,
            last
          });
        } catch (error) {
          res = error
          console.log("error found");
          setError(error.response.data.errorMessage);
        } 
        finally {console.log('res: ', res)} 
      };
    

    【讨论】:

    • 当请求正确并已发送到服务器时,我没有得到控制台日志```没有错误```。
    • 使用第二种方法,看看你得到了什么。
    • 抱歉,发送请求后,我在控制台中没有收到任何内容。
    • 当我尝试您的沙盒时,响应需要很长时间才能恢复,然后出错。给它大约 30 秒,看看你是否看到同样的错误。
    • 我什至在本地尝试过,但它没有给我任何东西。
    猜你喜欢
    • 2015-08-10
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多