如何使用axios在前端显示错误体

问题描述 投票:0回答:1

我的快速API端点在这里:

@app.post("/api/signup", status_code=status.HTTP_200_OK)
async def signup( credentials : signupcred ):
  try: 
   print(credentials.email,  credentials.password1, credentials.name )
   response = account.create(email= credentials.email, password= credentials.password1, name = credentials.name , user_id= ID.unique() )

   return {response}

  except Exception as e: 
         raise HTTPException(status_code= status.HTTP_403_FORBIDDEN)  # Return an appropriate error status code

在前端,我想在引发异常后打印响应,因为响应很好地解释了错误。我不想向用户发送 http 错误代码。

我的前端是:

const handlesignup = async (e: any) => {
  e.preventDefault();
  setLoading((loading) => !loading);
  try {
    const signupresponse = await axios.post("/api/signup", {
      email: signupemail,
      password1: password1,
      name: name,
    }); // Send as query paramers );
    // const loginresponse = await axios.post('/api/login', {email, password} )// Send as query paramers );
    // setIsloggedin(()=> true)
    router.replace("/dashboard");
    setLoading((loading) => !loading);
  } catch (error) {
    alert(error);
  }
};

console.log 不起作用,因为我使用带有快速 api 后端的 nextjs。我只想将创建函数的响应打印到前端,以便用户知道为什么会发生函数错误。目前警报显示: AxiosError:请求失败,状态代码 403

javascript typescript next.js fastapi
1个回答
0
投票

如果我理解正确的话,你想使用另一个

useState
,所以在
.catch(error)
中你可以
setError(error)
,然后在返回的组件中你可以显示它......

return (
    <div> 
        ...
        {error && error.response.data.message}
    </div>
);

我不知道 AxiosResponse 中消息的确切路径,但如果您使用 Typescript,则可以按 F12 并按照类型进行操作。

© www.soinside.com 2019 - 2024. All rights reserved.