Flask接口传参报错:JS向Python传值遇415/400错误求排查
问题排查与解决方案
核心问题分析
你遇到的415/400错误,本质是跨域请求拦截和请求头格式不规范导致Flask无法正确解析JSON payload,具体原因如下:
- 跨域资源共享(CORS)限制:如果前端页面是直接打开本地HTML文件(
file://协议)或运行在其他端口,浏览器会拦截跨域请求,导致实际发送的请求头、body被篡改,Flask无法识别application/json类型。 - 请求头格式错误:单独设置
Charset头无效,标准JSON请求的Content-Type需要合并字符集参数。 - Postman测试配置错误:测试时未正确设置
Content-Type为application/json,导致服务端返回415。
分步修复方案
1. 给Flask添加CORS支持
安装flask-cors并配置,允许跨域请求:
from flask import Flask, request, jsonify from flask_cors import CORS # 执行 pip install flask-cors 安装 app = Flask(__name__) CORS(app) # 开发环境允许所有跨域请求,生产环境可指定具体域名 @app.route('/receive-data', methods=['POST']) def receive_data(): # 先校验Content-Type if request.headers.get('Content-Type') != 'application/json; charset=UTF-8': return jsonify({"error": "Content-Type must be application/json; charset=UTF-8"}), 415 # 使用silent=True避免解析失败时抛出异常 data = request.get_json(silent=True) if data is None: return jsonify({"error": "Invalid or empty JSON payload"}), 400 variable = data.get('variable') print(f"Received variable from JavaScript: {variable}") return jsonify({"status": "success", "received_variable": variable}) if __name__ == '__main__': app.run(debug=True)
2. 修正JavaScript请求代码
调整请求头格式,简化逻辑并确保每次状态变化都发送请求:
let beatcheckbox = false let clonecheckbox = false document.getElementById("beatcb").addEventListener("change", function() { beatcheckbox = this.checked; console.log(`beat checkbox is ${beatcheckbox ? 'checked' : 'not checked'}`); fetch('http://127.0.0.1:5000/receive-data', { method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', // 合并字符集参数 'Accept': 'application/json' }, body: JSON.stringify({ variable: beatcheckbox }) }) .then(response => { if (!response.ok) { // 优先解析JSON错误, fallback到文本 return response.json().catch(() => response.text()).then(err => { throw new Error(`HTTP ${response.status}: ${err}`); }); } return response.json(); }) .then(data => { console.log('Response from server:', data); }) .catch((error) => { console.error('Error:', error); }); }); document.getElementById("clonecb").addEventListener("change", function() { clonecheckbox = this.checked; console.log(`clone checkbox is ${clonecheckbox ? 'checked' : 'not checked'}`); });
3. Postman测试正确配置
- 请求方法选择
POST - 在
Headers中添加:Content-Type: application/json - 在
Body中选择raw->JSON,输入测试内容:{"variable": true}
验证步骤
- 启动Flask服务
- 打开前端页面(确保不是
file://协议,可通过Flask托管静态文件或用本地服务器打开) - 勾选/取消
beatcb复选框,查看浏览器控制台和Flask终端的输出
内容的提问来源于stack exchange,提问作者MaxHorizonai
相关产品推荐
相关产品推荐

