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

JQuery Ajax POST请求报405(Method Not Allowed)错误求助

解决POST请求405 (Method Not Allowed)问题

错误原因

405错误的核心是你当前使用的服务器(端口5500通常是Live Server这类静态文件服务器)不允许对/api/orders资源使用POST方法。静态服务器仅支持GET请求读取静态文件(比如你的JSON文件),没有处理POST请求的能力,因此会返回方法不允许的错误。

解决方案

1. 搭建简单后端服务处理POST请求

如果只是为了测试AJAX的POST功能,用Node.js的Express框架快速搭建后端:

  • 步骤1:在项目根目录打开终端,执行:
    npm init -y
    npm install express cors
    
  • 步骤2:创建server.js文件,写入以下代码:
    const express = require('express');
    const cors = require('cors');
    const app = express();
    const port = 5500;
    
    app.use(cors());
    app.use(express.json());
    
    // 模拟存储订单的数组
    let orders = [];
    
    // 处理GET请求,返回订单列表
    app.get('/api/orders', (req, res) => {
        res.json(orders);
    });
    
    // 处理POST请求,添加新订单
    app.post('/api/orders', (req, res) => {
        const newOrder = req.body;
        orders.push(newOrder);
        res.status(201).json(newOrder);
    });
    
    app.listen(port, () => {
        console.log(`服务器运行在 http://localhost:${port}`);
    });
    
  • 步骤3:启动服务器:
    node server.js
    
  • 步骤4:修改你的AJAX代码(建议用绝对路径/api/orders,避免相对路径问题):
    $.ajax({
        type: "POST",
        url: "/api/orders",
        data: JSON.stringify({name: 'John', drink: 'Beer'}),
        contentType: "application/json",
        success: function (newOrder) {
            console.log('success', newOrder);
        },
        error: function(xhr){
            console.log('错误详情:', xhr.responseText);
            alert("Error Saving New Order");
        }
    });
    

2. 确认请求路径正确性(已验证没问题)

你的HTML路径是localhost:5500/JsHtmlCss/JqueryAjaxTutorial/index.html,../../api/orders解析后正好是localhost:5500/api/orders,和你提供的JSON文件位置一致,路径不存在问题。

3. 调整请求内容类型(辅助优化)

如果后端期望接收JSON格式的数据,需要在AJAX配置里添加contentType: "application/json",并将data转为JSON字符串(如上面代码所示)。不过这不是解决405错误的关键,核心还是后端需要支持POST方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:45:35