【问题标题】:Uncaught (in promise) Error: Network Error at createError未捕获(承诺中)错误:createError 处的网络错误
【发布时间】:2022-01-03 07:46:17
【问题描述】:

我将使用 Axios 来通信 API。 但是这种错误不断出现。我不明白这个问题。我在互联网上搜索并尝试了一切。帮我。 我只想点击那个按钮来查看开发者工具中的低价值。

  useEffect(() => {
    setJwt(getClientCookieFromClient('jwt'));
  }, []);

  const customFetch = async () => {
    const res = await axios
      .get(`${process.env.NEXT_PUBLIC_WECODE_URI}/subscription/master_table`, {
        headers: {
          Authentication: jwt,
        },
      })
      .then((res) => res.data);
    if (!res.data.success) {
      alert(res.data.message);
    }
  };

...

<button onClick={() => customFetch()}>API호출버튼</button>

【问题讨论】:

  • .then 行之后,添加.catch(e) {console.error(e)}。这将通过记录错误来处理错误,并有望提供有关问题所在的更多详细信息。
  • remove ".then((res) => res.data);",该部分将“data”分配给“res”,这使您的 if 语句失败。
  • @user2740650 语法为.catch(e =&gt; console.error(e))

标签: javascript reactjs typescript next.js


【解决方案1】:

总是将 await 包裹在 try/catch 块中。

const customFetch = async () => {
  try {
    const res = await axios
      .get(`${process.env.NEXT_PUBLIC_WECODE_URI}/subscription/master_table`, {
        headers: {
          Authentication: jwt,
        },
      })
      .then((res) => res.data);
    if (!res.data.success) {
      alert(res.data.message);
    }
  } catch (error) {
    console.log(error);
    // Do something with error
  }
};

【讨论】:

    【解决方案2】:

    试试

    useEffect(() => {
      setJwt(getClientCookieFromClient('jwt'));
    }, []);
    
    const customFetch = async () => {
      const res = await axios.get(`${process.env.NEXT_PUBLIC_WECODE_URI}/subscription/master_table`, {
        headers: {
          Authentication: jwt,
        },
      });
      if (!res.data.success) {
        alert(res.data.message);
      }
    };
    
    

    【讨论】:

      【解决方案3】:

      注意:

      不确定您的响应结构。当前代码按预期的结构工作:

      res = { data: { data: {success: true}}}
      

      如果不是这样,则使用if 语句作为!res.success


      useEffect(() => {
          setJwt(getClientCookieFromClient('jwt'));
        }, []);
      
        const customFetch = async () => {
          const res = await axios
            .get(`${process.env.NEXT_PUBLIC_WECODE_URI}/subscription/master_table`, {
              headers: {
                Authentication: jwt,
              },
            })
            .then((res) => res.data)
            .catch((err) => console.log("Error while fetching",err)); //<--- use .catch for catching error
          if (!res.data.success) {
            alert(res.data.message);
          }
        };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-30
        • 2019-04-09
        • 1970-01-01
        • 2022-12-19
        • 2016-12-20
        • 1970-01-01
        • 2021-03-03
        • 2021-02-01
        相关资源
        最近更新 更多