使用Ajax从HTML向Node.js发送数据时遇405错误求助
问题分析与修复方案
核心问题:端口不匹配导致405错误
你的Node.js服务器运行在3000端口,但前端AJAX请求的是http://127.0.0.1:5500/(5500通常是Live Server等静态文件服务器的端口),请求根本没发送到你的Node.js服务器,因此触发405方法不允许错误。
分步修复
1. 修正前端AJAX配置
修改请求地址、contentType及数据格式:
$.ajax({ url: 'http://localhost:3000/', // 改为Node.js服务器的3000端口 type: 'POST', contentType: 'application/json', // 明确告知服务器发送JSON格式数据 dataType: "json", data: JSON.stringify({output_list: output_list}), // 直接序列化整个对象 success: function (res) {console.log("Output list transferred successfully") }, error: function (err) { console.log("Transfer is not successful") }, });
2. 修复Node.js后端代码
解决未定义变量、重复响应及跨域问题:
const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // 处理跨域(若前端与服务器端口不同时需要) app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); app.get("/", function (req, res) { res.sendFile(__dirname + "/Router36x36.html"); }); app.post("/", function (req, res) { // 从请求体中获取前端发送的数组 const receivedList = req.body.output_list; console.log("收到的数组:", receivedList); // 仅发送一次响应 res.status(200).json({ message: "Thanks for posting these", received: receivedList }); }); app.listen(3000, function () { console.log("Server is running on port 3000"); });
3. 正确运行方式
- 启动Node.js服务器:终端进入项目目录,执行
node 你的服务器文件名.js - 访问页面:浏览器打开
http://localhost:3000/,不要通过其他静态文件服务器(如Live Server)打开,避免端口不匹配
内容的提问来源于stack exchange,提问作者Adnan Sen
相关产品推荐
相关产品推荐

