FastAPI中Delete请求在浏览器触发405 Method Not Allowed错误
问题描述
在SwaggerUI中调用删除分支的API可正常执行,但在浏览器直接访问http://127.0.0.1:8000/delete_branch/3时,返回405 Method Not Allowed错误。日志显示请求方法自动转为GET,分支2和3均已存在。
日志信息
INFO: 127.0.0.1:64422 - "DELETE /delete_branch/2 HTTP/1.1" 200 OK INFO: 127.0.0.1:64429 - "GET /delete_branch/3 HTTP/1.1" 405 Method Not Allowed
代码实现
@app.delete("/delete_branch/{branch_id}") def delete_branch(branch_id: int): if branch_id not in branches: raise HTTPException(status_code=404, detail="Branch not found") del branches[branch_id]
原因
浏览器地址栏直接输入URL发起的请求默认是GET方法,而你的API通过@app.delete装饰器限定了仅接收DELETE请求,因此会返回405错误。SwaggerUI能正常调用是因为它会按API定义发送DELETE请求。
解决办法
- 不要直接在浏览器地址栏访问删除接口,改用以下方式发送
DELETE请求:- 表单提交:创建表单指定
method="POST",同时添加隐藏字段_method="DELETE"(需框架支持方法重载,比如Flask的method-override扩展); - JavaScript脚本:用
fetch或axios发送请求:fetch('http://127.0.0.1:8000/delete_branch/3', { method: 'DELETE' })
- 表单提交:创建表单指定
- 临时兼容GET请求(不推荐,违反REST规范,GET操作应无副作用):
@app.route("/delete_branch/{branch_id}", methods=["DELETE", "GET"]) def delete_branch(branch_id: int): if branch_id not in branches: raise HTTPException(status_code=404, detail="Branch not found") del branches[branch_id]
内容的提问来源于stack exchange,提问作者KurczakChrupiacy2
相关产品推荐
相关产品推荐

