Flask API POST请求报415 Unsupported Media Type错误的排查与解决
解决Flask API POST请求的415 Unsupported Media Type错误
错误信息
{
"error": "415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not 'application/json'."
}
原因排查与解决方法
1. 修复后端CORS配置冲突
你的后端同时使用了全局CORS配置、@cross_origin()装饰器和@after_request手动添加响应头,多重配置可能导致请求头处理异常。建议简化配置:
- 移除
@after_request中的自定义CORS头,flask-cors库已自动处理跨域响应头 - 保留全局CORS配置,移除路由上的
@cross_origin()装饰器
修改后的后端核心配置代码:
app = Flask(__name__) # 全局统一配置CORS,覆盖所需规则 CORS(app, resources={r"/*": { "origins": "https://yellowsense.in", "allow_headers": ["Content-Type", "Authorization"], "methods": ["GET", "POST"] }}) # 移除原有的@app.after_request函数 # 移除路由上的@cross_origin()装饰器 @app.route('/society_names', methods=['GET']) def get_society_names(): # 原有代码保持不变 ... @app.route('/insert_maid', methods=['POST']) def insert_maid(): # 原有代码保持不变 ...
2. 确保前端请求头正确发送
虽然前端代码中设置了Content-Type: application/json,但可以通过更严谨的方式定义请求头,避免浏览器自动修改:
function sendDataToFormester(data) { const formesterFormUrl = 'https://yellowsensebackendapi.azurewebsites.net/insert_maid'; fetch(formesterFormUrl, { method: 'POST', headers: new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' }), body: JSON.stringify(data) }) .then(response => { if (!response.ok) { return response.json().then(err => { throw err; }); } alert('Data submitted successfully to YellowSense.'); }) .catch((error) => { console.error('Error:', error); alert(`An error occurred: ${error.error || 'Unknown error'}`); }); }
3. 后端添加请求头验证(调试用)
在insert_maid路由中增加请求头检查,便于快速定位问题:
@app.route('/insert_maid', methods=['POST']) def insert_maid(): try: # 先验证请求头格式 if request.headers.get('Content-Type') != 'application/json': return jsonify({"error": "Content-Type must be application/json"}), 415 data = request.get_json() # 后续业务逻辑代码保持不变 ... except Exception as e: return jsonify({"error": str(e)})
4. 调试技巧
- 打开浏览器开发者工具(F12),切换到Network标签,查看POST请求的
Request Headers,确认Content-Type是否为application/json - 在后端代码中打印请求头,验证实际收到的请求信息:
print("Received Request Headers:", dict(request.headers))
内容的提问来源于stack exchange,提问作者Samirit Saha
相关产品推荐
相关产品推荐

