JavaScript代码无法向Flask服务器发送POST请求,求排查原因
问题:前端JS与Flask交互出现Failed to fetch错误,服务器无请求日志
环境代码
Flask服务器代码
from flask import Flask, request, jsonify from main import * app = Flask(__name__) @app.route('/', methods=['POST']) def do_classification(): try: data = request.get_json() user_input = data['input'] prediction = classify(user_input) print(f'Received input "{user_input}" from chat server') return jsonify({'prediction': prediction}) except Exception as e: return jsonify({'error': str(e)}) if __name__ == '__main__': app.run(port=5000, ssl_context='adhoc')
前端JavaScript代码
// Get the form and input elements const form = document.getElementById('message-form'); const input = document.getElementById('message-input'); // Add an event listener to the form form.addEventListener('submit', async (event) => { // Prevent the default form submission behavior event.preventDefault(); // Get the input value const message = input.value; // Create a new message element and add it to the output window const messageElement = document.createElement('div'); messageElement.textContent = message; document.getElementById('chat-window').appendChild(messageElement); input.value = ''; // send user input to the model try { const response = await fetch('https://localhost:5000/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ input: message }), }); if (!response.ok) { throw new Error('Request failed with status ' + response.status); } const result = await response.json(); const prediction = result.prediction; // Display the model's response in the chat window const modelMessageElement = document.createElement('div'); modelMessageElement.textContent = prediction; document.getElementById('chat-window').appendChild(modelMessageElement); } catch (error) { // Display the error message in the chat window const errorMessageElement = document.createElement('div'); errorMessageElement.textContent = 'Error: ' + error.message; document.getElementById('chat-window').appendChild(errorMessageElement); } });
现象
前端触发请求后提示Error: Failed to fetch,Flask终端无任何请求接收日志,预期的交互流程未执行。
排查与修复方案
1. Flask启动代码冲突(核心原因)
原代码存在两个if __name__ == '__main__'块,实际启动的是未启用SSL的app.run(port=5000),但前端请求用的是https://localhost:5000,协议不匹配直接导致请求失败。
修复:合并启动代码,确保SSL和端口参数同时生效(代码已在上方修正)。
2. 跨域资源共享(CORS)限制
如果前端页面从file://协议加载(直接本地打开HTML),或域名/端口与Flask服务器不一致,浏览器会拦截跨域请求,服务器根本收不到请求。
修复:安装并启用Flask-CORS扩展:
- 执行安装命令:
pip install flask-cors - 在Flask代码中添加CORS配置(代码已在上方修正)。
3. 前端响应解析优化
Flask返回的是JSON格式,原代码用response.text()解析会得到原始JSON字符串,改为response.json()可以直接获取结构化数据(代码已在上方修正)。
4. 基础校验
- 确认Flask启动日志显示
* Running on https://127.0.0.1:5000,确保HTTPS和端口正确 - 检查前端请求URL是否与服务器地址完全一致,避免协议(http/https)或端口写错
内容的提问来源于stack exchange,提问作者goth gamer gal
相关产品推荐
相关产品推荐

