You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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请求:
    1. 表单提交:创建表单指定method="POST",同时添加隐藏字段_method="DELETE"(需框架支持方法重载,比如Flask的method-override扩展);
    2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 17:22:32