React从FastAPI下载.csv文件时出现405 Method Not Allowed错误
解决405 Method Not Allowed错误并实现CSV下载
错误原因
你的FastAPI接口定义为POST方法(@app.post("/genreport")),但React中fetch默认发起GET请求,请求方法不匹配导致服务器返回405错误。
解决方案
方案1:将FastAPI接口改为GET方法(推荐)
下载CSV属于资源获取操作,符合HTTP GET方法的语义,修改FastAPI代码的装饰器即可:
# 把@app.post替换为@app.get @app.get("/genreport") def gen_colreport(db: Session = Depends(get_db)): df = collection_report(db) date_today = datetime.today().strftime('%Y%m%d') col_report_str = "collectionreport_" filename = col_report_str + date_today + ".csv" stream = io.StringIO() df.to_csv(stream, encoding="utf-8", index= False) response = StreamingResponse(iter([stream.getvalue()]), media_type="text/csv" ) response.headers["Content-Disposition"] = "attachment; filename=%s" % (filename) return response
方案2:React中发起POST请求(若必须用POST)
如果接口需要接收POST参数,修改React的fetch代码,显式指定请求方法为POST:
downloadData = () => { fetch('http://localhost:8000/genreport', { method: 'POST', // 指定POST请求方法 // 若需要传参数,可添加headers和body,示例: // headers: { 'Content-Type': 'application/json' }, // body: JSON.stringify({ param: 'value' }) }) .then(response => { if (!response.ok) throw new Error('请求失败'); return response.blob(); }) .then(blob => { let url = window.URL.createObjectURL(blob); let a = document.createElement('a'); a.href = url; // 可从响应头获取服务器指定的文件名,替代硬编码 const contentDisposition = response.headers.get('Content-Disposition'); const filename = contentDisposition?.split('filename=')[1] || 'onomonitoring.csv'; a.download = filename; a.click(); // 清理URL对象,避免内存泄漏 window.URL.revokeObjectURL(url); }) .catch(err => console.error('下载出错:', err)); }
关于直接从数据库获取文件的建议
不建议前端直接连接数据库,这会暴露数据库凭证和结构,带来严重安全风险。保持现有架构(前端请求FastAPI,FastAPI从数据库取数生成CSV)是更安全、规范的做法。
内容的提问来源于stack exchange,提问作者Erlene Chua
相关产品推荐
相关产品推荐

