Flask视图函数返回无效响应错误排查求助
问题分析与解决
核心错误点
请求参数获取方式不匹配
前端通过Content-Type: application/json发送JSON格式的POST数据,但后端用request.args.get()提取参数——request.args仅用于获取URL中的查询参数(如?key=value形式),完全读不到请求体里的JSON内容。这直接导致title、description等变量全部为None,触发if not ...分支,执行空return(返回None),从而抛出TypeError。空return导致无效响应
代码中参数缺失的分支仅写了return,没有返回任何Flask认可的响应对象(如jsonify、字符串、响应实例),违反了Flask视图函数的返回要求。
修复步骤
1. 修正参数获取逻辑
用request.get_json()解析JSON请求体,替换错误的request.args.get():
@app.route("/createblog", methods=["POST"]) def createblog(): # 解析JSON请求体,非JSON请求会返回None post_data = request.get_json() if not post_data: return jsonify(status=400, message="请求格式错误,需为JSON") title = post_data.get("title") description = post_data.get("description") content = post_data.get("content") username = post_data.get("username") password = post_data.get("password")
2. 修复空return问题
给参数缺失的分支返回合法响应:
if not title or not description or not content or not username or not password: return jsonify(status=400, message="必填参数缺失")
3. 完整修复后的代码
@app.route("/createblog", methods=["POST"]) def createblog(): post_data = request.get_json() if not post_data: return jsonify(status=400, message="请求格式错误,需为JSON") title = post_data.get("title") description = post_data.get("description") content = post_data.get("content") username = post_data.get("username") password = post_data.get("password") if not title or not description or not content or not username or not password: return jsonify(status=400, message="必填参数缺失") cursor.execute("INSERT INTO blogs (poster_id, title, description, content) VALUES ((SELECT id FROM users WHERE username=? AND password=?), ?, ?, ?)", (username, password, title, description, content)) connection.commit() return jsonify(status=200)
注册功能正常的原因
注册接口用request.form.get()获取参数,说明注册前端是通过表单(application/x-www-form-urlencoded格式)提交数据,和后端的参数获取方式匹配;而博客创建用JSON格式提交,后端却用了错误的查询参数获取方式,这是两者的核心差异。
注意:直接在SQL中传递明文密码存在严重安全风险,建议使用
werkzeug.security的generate_password_hash和check_password_hash对密码进行哈希处理后再存储、校验,不要直接操作明文密码。
内容的提问来源于stack exchange,提问作者Ayyy nonomusCoder
相关产品推荐
相关产品推荐

