'Flask correct way to handle errors with AJAX call from front end
I have a React app that communicates with a Python Flask server.
I am implementing a feature that allows a user to change their password. An AJAX request is made from React to Flask. This sends the old password and the new password.
I do all checks on front end to ensure that the password meets the requirements.
After the data is sent from the front end Flask then checks that the old password is correct and then updates the new password. This sends a 200 response back to the client. When everything is successful I have no issues.
However, I am unsure of what to do in the situation where the user sends 200 status, but the json message returned is different.
My question really is whether an error response should be sent here at this stage.
This is what my code looks like
@customer.route('/update-password', methods=['POST'])
def update():
current_password=request.json['currentPassword']
password=request.json['newPassword']
login_response = engine.login('testUser', current_password)
if login_response.get('success'):
password_response = engine.update_user_password(password=password)
if password_response.get('success'):
return jsonify(message='password_updated_success')
else:
return jsonify(message='password_update_error')
else:
return jsonify(message='incorrect_password_provided')
And here is my front end code
axios.post('update-password', {
currentPassword: oldPassword,
newPassword: newPassword
}).then(response => {
dispatch(updatePasswordSuccess());
resolve(response);
}).catch(err => {
dispatch(updatePasswordError());
reject(err);
});
Solution 1:[1]
Change your response structure to explicitly send one of the relevant HTTP Error codes (like 500) to your front end code so the AJAX will identify an error has occurred.
Basically something like this:
return jsonify(message='password_update_error'),500
See Flask Documentation here for further information on this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ty Hitzeman |
