如何配置Node.js Express服务器接收POST请求并解决405错误?
405 (Method Not Allowed) 错误解决方法
1. 核对前后端端口
前端请求地址是http://127.0.0.1:5500/genQuestions,确认Express后端运行在5500端口,否则修改前端请求地址或后端端口:
// 后端设置端口为5500 const PORT = 5500; app.listen(PORT, () => console.log(`服务器运行在端口${PORT}`));
2. 添加上请求体解析中间件
前端发送JSON格式数据,后端必须用express.json()解析请求体,否则可能导致路由匹配异常:
const express = require('express'); const app = express(); const cors = require('cors'); // 中间件顺序不能错:先CORS,再解析JSON app.use(cors()); app.use(express.json()); // 挂载POST路由 app.post('/genQuestions', async (req, res) => { const formData = req.body; // 生成题目逻辑 res.status(200).json({ message: '请求成功', data: formData }); // 必须返回响应 });
3. 显式配置CORS允许POST方法
若默认CORS配置未生效,直接指定允许的HTTP方法:
app.use(cors({ methods: ['GET', 'POST', 'OPTIONS'], allowedHeaders: ['Content-Type'] }));
4. 检查路由与服务器状态
- 确保
app.post('/genQuestions')路由挂载在所有中间件之后。 - 修改后端代码后重启服务器,新配置才会生效。
5. 前端请求优化排查
- 确认
formObj是合法JSON对象,无循环引用或非法值。 - 添加错误捕获定位问题:
await fetch('http://127.0.0.1:5500/genQuestions', { method: 'POST', headers: { "Content-type": "application/json" }, body: JSON.stringify(formObj), }) .then(response => { if (!response.ok) throw new Error(`HTTP错误:状态码${response.status}`); return response.json(); }) .then(data => console.log(data)) .catch(err => console.error('请求失败:', err));
内容的提问来源于stack exchange,提问作者Joseph Nwodo
相关产品推荐
相关产品推荐

