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

Access-Control-Allow-Origin未更新且出现405 Method Not Allowed问题求助

解决405 Method Not Allowed错误

问题原因分析

你遇到的405错误来自页面中的表单提交操作:

  • 表单未设置action属性,点击提交按钮时会向当前前端页面的URL发送POST请求,但前端静态服务器(比如Live Server)不支持POST方法,因此返回405错误。
  • 后端的POST接口未返回任何响应,即使请求成功到达后端,前端也会收到空响应。

具体修复步骤

1. 修正表单提交目标(若需用表单测试POST接口)

给表单添加action属性指向后端地址,同时阻止页面默认跳转行为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body onload="start()">
<form method="post" action="http://localhost:5500/" onsubmit="handleSubmit(event)">
    <button style="height: 50px; width: 50px;" type="submit"></button>
</form>
</body>
</html>
<script>
    function start(){
        fetch("http://localhost:5500/")
.then(res => res.json())
.then(data => console.log(data))
    }

    function handleSubmit(e) {
        e.preventDefault(); // 阻止页面默认跳转
        fetch("http://localhost:5500/", { method: "POST" })
          .then(res => res.text())
          .then(data => console.log(data))
    }
</script>

2. 完善后端POST接口的响应

在后端POST路由中添加返回响应的代码,避免前端收到空响应:

const express = require("express")
const app = express()
const cors = require("cors")
app.use(cors({
    origin: "*"
}))

app.get("/", (req, res) => {
    res.json({name: "lukas"})
})

app.post("/", (req, res) => {
    console.log("hej")
    res.json({status: "success", message: "POST请求已处理"}) // 添加响应内容
})

// 启动服务器(之前代码遗漏的关键步骤)
app.listen(5500, () => {
    console.log("服务器运行在http://localhost:5500")
})

3. 可选:移除无用表单(若不需要表单功能)

如果页面中的表单是多余的,直接删除表单和按钮,只保留fetch请求逻辑即可,彻底避免错误的POST请求触发。

内容的提问来源于stack exchange,提问作者ottdevott

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:35:21