could you please tell me how to show error message in react js when http request send ?
I make a service in the nodejs where I am sending 400
status with error message
. I want to show this error message on frontend
.
app.get('/a',(req,res)=>{
res.status(400).send({message:" some reason error message"})
})
Now I want to show this error message on frontend .on catch I will not get this message
.
try {
const r = await axios.get('http://localhost:3002/a');
} catch (e) {
console.log('===============================================')
console.log(e)
console.log(e.data)
hideLoading();
setErrorMessage(e.message);
showErrorPopUp();
}
on catch
i will not get this message.getting on stack of error
[![enter image description here][1]][1]
Make the api call, the server (assuming you are also building the server) should check to see if the name and phone number already exist. If they already exist the server should return an error. In your react app catch the error after your API call and assign it to your state variable for error.
In order to display error messages on forms, you need to consider the following four basic rules: The error message needs to be short and meaningful. The placement of the message needs to be associated with the field. The message style needs to be separated from the style of the field labels and instructions.
It's better to respond with a JSON in this particular case from the server:
app.get('/a',(req,res) => {
res.status(400).json({message:"some reason error message"})
})
So in the client, you can read from error.response
easily
try {
const r = await axios.get('http://localhost:3002/a');
} catch (e) {
if (e.response && e.response.data) {
console.log(e.response.data.message) // some reason error message
}
}
Read more about handling caught errors in axios here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With