Flask对接Chrome扩展钓鱼检测工具时出现500内部服务器错误
问题排查与解决方案
先明确两个错误的核心原因:
- 405错误:前后端请求方法不匹配,或后端未正确配置允许POST请求
- 500错误:后端处理请求时发生未捕获异常,或跨域问题导致请求被拦截
步骤1:处理跨域问题(Chrome扩展必做)
Chrome扩展的popup页面与Flask后端属于跨域环境,必须配置CORS:
- 安装依赖:
pip install flask-cors
- 改造backend.py:
from flask import Flask, request, jsonify from flask_cors import CORS app = Flask(__name__) # 开发阶段允许所有域名请求,生产环境请指定具体域名 CORS(app) @app.route('/scan', methods=['POST']) def scan_phish(): try: # 解析前端发送的JSON数据 data = request.get_json() if not data or 'email_content' not in data: return jsonify({'error': '缺少邮件内容参数'}), 400 # 替换为你的钓鱼邮件检测逻辑 email_content = data['email_content'] is_phish = '钓鱼' in email_content or '账户验证' in email_content # 示例判断 return jsonify({'is_phishing': is_phish, 'message': '分析完成'}) except Exception as e: # 捕获异常并返回具体错误,避免无提示的500错误 return jsonify({'error': str(e)}), 500 if __name__ == '__main__': app.run(debug=True)
步骤2:修正前端popup.js请求逻辑
确保请求方法、数据格式与后端匹配:
document.getElementById('scan-btn').addEventListener('click', async () => { const emailContent = document.getElementById('email-content').value; if (!emailContent) { alert('请先提取邮件内容'); return; } try { const response = await fetch('http://localhost:5000/scan', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email_content: emailContent }) }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || `请求失败:${response.status}`); } const result = await response.json(); alert(result.is_phishing ? '检测到钓鱼邮件!' : '邮件安全'); } catch (err) { console.error('扫描出错:', err); alert(`扫描失败:${err.message}`); } });
步骤3:额外排查项
- 确认后端服务正常运行:访问
http://localhost:5000/scan(GET请求返回405是正常的,因为路由仅允许POST) - 检查Chrome扩展的manifest.json是否配置了后端域名权限:
{ "permissions": [ "activeTab", "http://localhost:5000/*" ] }
- 开启后端debug模式(
app.run(debug=True)),可在控制台查看500错误的具体堆栈信息,快速定位代码问题
内容的提问来源于stack exchange,提问作者Kaze
相关产品推荐
相关产品推荐

