Issue
My Project has been built with Frontend is React.js and Backend is Python-Flask.
When I try to login by using existing user info on Chrome Browser, I am getting one error below.
Bad Request The browser (or proxy) sent a request that this server could not understand.
And then, when I check api with same user info on Postman, it returns the success results.
Here is my codebase.
Login Function on Frontend.
export const login = async (email: string, password: string) => {
const token = await fetch(`${API_URL}/login`, {
method: "POST",
mode: 'cors',
body: JSON.stringify({
email,
password
})
}).then(res => res.json())
return token
}
Login Route on Python-Flask Backend
@auth.route('/login', methods=['POST'])
def login():
post_data = request.get_json()
try:
user = User.query.filter_by(email = post_data.get('email')).first()
if user and bcrypt.check_password_hash(
user.password, post_data.get('password')
):
auth_token = create_access_token(identity=post_data.get('email'))
if auth_token:
responseObject = {
'status': 'success',
'message': 'Successfully logged in.',
'auth_token': auth_token,
'user': user.toObject()
}
return jsonify(responseObject), 200
else:
responseObject = {
'status': 'fail',
'message': 'User does not exist'
}
return jsonify(responseObject), 404
except Exception as e:
responseObject = {
'status': 'fail',
'message': 'Try again'
}
return jsonify(responseObject), 500
What is wrong here? Why I am getting good return values on Postman, but I am getting Bad Request Error on Browser?
Please help me.
Solution
Maybe I found a solution to fix the Bad Request 400 error problem above. It was a front-end issue, not a back-end issue.
I updated the login function
as shown below.
Old Login Function:
export const login = async (email: string, password: string) => {
const token = await fetch(`${API_URL}/login`, {
method: "POST",
mode: 'cors',
body: JSON.stringify({
email,
password
})
}).then(res => res.json())
return token
}
Updated Login Function:
export const login = async (email: string, password: string) => {
const apiUrl = API_URL + '/auth/login'
const requestOptions: any = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password
})
}
const token = await fetch(apiUrl, requestOptions)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok')
}
console.log('Login Token Response', response)
return response.json()
})
.catch(error => {
console.error('Error:', error)
})
return token
}
After updating like this, Bad Request Error disappeared.
If you have a better solution, please let me know.
Thanks.
Answered By - SWS-5007
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.