Express JS中Post方法req.body始终为undefined的问题求助
Express POST请求中req.body返回undefined的解决方法
问题场景
配置了app.use(express.json())后,POST请求的req.body仍返回undefined,相关代码、请求示例及错误输出如下:
原代码
const express = require("express"); const path = require("path"); const { open } = require("sqlite"); const sqlite3 = require("sqlite3"); const dbPath = path.join(__dirname, "moviesData.db"); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true })) let database = null; const initializeDBAndServer = async () => { try { database = await open({ filename: dbPath, driver: sqlite3.Database, }) app.listen(5353, () => { console.log(`server is running at http://localhost:5353/`) }) } catch (error) { console.log(`error: ${error.message}`); process.exit(1) } } initializeDBAndServer(); app.post("/myId", async (req, res) => { const { id } = req.body; console.log(`requested Id is ${id}`); res.send(`requested Id id ${id}`); })
原请求示例
POST http://localhost:5353/myId/ Content-Type: "application/json" { "id": 123456 }
错误输出
requested Id is undefined
问题原因
- 请求头格式错误:
Content-Type字段带了多余的双引号,正确的Content-Type: application/json不需要加引号,引号会导致Express的JSON解析器无法识别请求体格式,从而无法解析出req.body。 - 路由定义为
/myId,但请求URL是/myId/(末尾多了斜杠),虽然Express默认会处理这种情况,但严格匹配时可能引发不必要的重定向干扰。
修正后的完整代码
const express = require("express"); const path = require("path"); const { open } = require("sqlite"); const sqlite3 = require("sqlite3"); const dbPath = path.join(__dirname, "moviesData.db"); const app = express(); // 只保留JSON解析中间件即可,urlencoded用于处理表单数据,此处无需配置 app.use(express.json()); let database = null; const initializeDBAndServer = async () => { try { database = await open({ filename: dbPath, driver: sqlite3.Database, }); app.listen(5353, () => { console.log(`server is running at http://localhost:5353/`); }); } catch (error) { console.log(`error: ${error.message}`); process.exit(1); } }; initializeDBAndServer(); app.post("/myId", async (req, res) => { const { id } = req.body; console.log(`requested Id is ${id}`); // 修正响应中的拼写错误(原代码是"id id") res.send(`requested Id is ${id}`); });
正确的请求格式
POST http://localhost:5353/myId Content-Type: application/json { "id": 123456 }
验证要点
- 确保请求的
Content-Type字段没有多余的双引号 - 保持请求URL与路由定义一致(
/myId而非/myId/) - 移除不需要的
express.urlencoded()中间件,避免不必要的解析干扰
内容的提问来源于stack exchange,提问作者King Kiran
相关产品推荐
相关产品推荐

