This is kind of a two part question, the first being specific to my personal circumstance and the second being an overall understanding of how things function.
I am performing a password reset for my application. The email gets sent along with a jwt
attached to the URL. After the user clicks the URL they are taken to the reset password page that fires of an action with the jwt
through componentWillMount
function. This action then fires off the fetch
:
static verifyResetPasswordToken(token) {
const obj = JSON.stringify(token);
return fetch('/api/auth/verifyResetPasswordToken', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
body: obj
})
.then(res => {
console.log('THEN');
})
.catch(error => {
console.log('CATCH');
});
}
On the API I'm handling this by taking the token passed in the body and checking if it has expired or not:
export function verifyResetPasswordToken(req, res, next) {
const token = jwt.decode(req.body.token);
if (token.exp > Date.now() / 1000) {
res.status(200).json();
} else {
res.status(401).json();
}
}
NOTE I understand this is not a secure way to check the validity of a token. I just need to figure out if it is expired or not.
Here is where the confusion lies. When the 401
status gets returned, my promise is rejected. It is my understanding that fetch
does not handle errors this way. That the only thing fetch
catches is network connectivity
and that I should still hit my then()
block even with 400 & 500 http status errors. Any idea as to why my promise is getting rejected with a 401
status? Why am I landing in the catch
block? How do I avoid this from happening? How do I handle different status that I want to respond with on my server?
My second question revolves around all of this. What is the best practice for handling server errors when working with fetch
and maybe specifically React
Redux
? This is my first time using fetch
and any light that can be shed to understanding how I should handle server side errors would be greatly appreciated.
static verifyResetPasswordToken(token) {
const obj = JSON.stringify(token);
return fetch('/api/auth/verifyResetPasswordToken', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
body: obj
})
.then(res => {
if(res.ok) {
console.log('THEN');
} else {
console.log('ELSE');
}
})
.catch(error => {
console.log('CATCH');
});
}