My fast api end point is here:
@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
on the front end, i want to print the response after an exception has been raised because the response explains the error well. I don’t want to send a http error code to the user.
my front end is :
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);
}
};
The console.log doesnt work because im using nextjs with fast api backend. I just want to print the response from the create function to the front end so users know why the function error has occurred. At the moment the alert shows: AxiosError: Request failed with status code 403
2
Answers
If I understand correctly, you want to use another
useState<AxiosResponse>()
so in the.catch(error)
you cansetError(error)
, then in the returned component you can display it…I don’t know the exact path to the message in AxiosResponse but if you’re on Typescript you can F12 on it and follow the types.
See Axios – Handling Errors
You can access the response body via
error.response?.data
.To display it in your Next.js component, you’d typically just use React state, for example