Users can input an email into an input field, which is then sent as a post request to an API using the following code:
try {
const res = await fetch("/api/email-registration", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
emailValue: emailValue,
}),
})
if (!res.ok) throw new Error(res.status);
const data = await res.json();
setMessage(data.message)
}
catch (err) {
console.log(err)
}
The post request is functioning properly. However, I am now attempting to access the error response JSON when intentionally creating an error to trigger the catch (err)
block.
One of the predefined error messages is:
res.status(409).json({
message: "This email has already been registered",
})
In the network tab, I can see the response status 409 and the response JSON with the specified value. When trying err.message
, only 409
is returned. My goal is to access the JSON value
{"message":"This email has already been registered"}
.
Is there a method to retrieve the error response message?
I simply want to display this specific JSON message to the user. Until now, I have used an if statement to check for 409
and display text based on the status code. However, I am interested in finding a way to access and display the JSON message from the post request error.