React+Flask项目登录功能浏览器报Bad Request错误求助
问题排查与解决
核心问题在于前端fetch请求缺少Content-Type: application/json请求头,导致Flask后端无法正确解析请求体。
原因分析
Postman发送JSON格式请求时,会自动为请求添加Content-Type: application/json头,Flask的request.get_json()方法依赖这个头来识别并解析JSON格式的请求体。但浏览器的fetch API在使用JSON.stringify()传递body时,不会默认设置该请求头,此时request.get_json()会返回None,后续调用post_data.get('email')会触发异常,最终返回400 Bad Request错误。
前端代码修复
在fetch请求中添加headers配置,明确指定请求体格式为JSON:
export const login = async (email: string, password: string) => { const token = await fetch(`${API_URL}/login`, { method: "POST", mode: 'cors', headers: { 'Content-Type': 'application/json' // 新增该请求头 }, body: JSON.stringify({ email, password }) }).then(res => res.json()) return token }
后端代码优化(可选)
可以在Flask路由中添加判断,避免post_data为None时抛出异常,增强接口鲁棒性:
@auth.route('/login', methods=['POST']) def login(): post_data = request.get_json() # 新增判断:若无法解析JSON,直接返回400错误 if not post_data: responseObject = { 'status': 'fail', 'message': 'Invalid request body. Expected JSON format.' } return jsonify(responseObject), 400 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 or password is incorrect' } return jsonify(responseObject), 404 except Exception as e: responseObject = { 'status': 'fail', 'message': 'Try again' } return jsonify(responseObject), 500
内容的提问来源于stack exchange,提问作者Super Boy
相关产品推荐
相关产品推荐

