ExpressJS中req.body返回undefined问题(已解决:参数顺序错误)
Express中req.body返回undefined问题排查与解决
问题说明
在使用Express内置解析器(或body-parser)处理表单POST请求时,req.body始终返回undefined,尝试访问req.body.city时触发错误:
TypeError: Cannot read properties of undefined (reading 'city')
此前同类项目中使用bodyParser可正常获取req.body.name,本次代码逻辑几乎一致却出现异常。
服务端代码
const express = require("express"); const app = express(); const https = require("https"); app.use(express.json()); app.use(express.urlencoded({ extended: true })); // const bodyParser = require("body-parser"); // app.use(bodyParser.json()); // app.use(bodyParser.urlencoded({ extended: true })); app.get("/", function (req, res) { res.sendFile(__dirname + "/index.html"); }); app.post("/", (res, req) => { console.log(req.body); //console.log(req.body.cityName); }); app.listen(3000, function () { console.log("Server is running on port 3000"); });
前端HTML代码
<body> <form action="/" method="post"> <label for="cityInput">City Name:</label> <input id="cityInput" type="text" name="cityName" placeholder="cityname"> <button type="submit" name="button">Submit</button> </form> </body>
解决方案
问题已解决!感谢Phil指正,原因是POST请求回调函数的参数顺序写反了:原本应该是(req, res),代码中写成了(res, req),导致实际的请求对象被当作响应对象使用,自然无法获取req.body。修正参数顺序后即可正常获取表单数据。
内容的提问来源于stack exchange,提问作者Jia Li
相关产品推荐
相关产品推荐

