Node.js-Express接收表单POST请求时req.body返回undefined问题
解决Express接收POST表单时req.body为空的问题
问题描述
使用Node.js/Express接收HTML表单POST请求时,req.body返回空对象,获取的字段值为undefined。已引入body-parser中间件,检查过表单的action与method配置,问题仍未解决。
代码示例
Node.js代码
const express = require('express') const bodyParser = require('body-parser') const app = express() const port = '3000' app.use(bodyParser.urlencoded({ extended: true})) app.use(bodyParser.json()); app.use(express.static('public')) app.get('/',function(req, res) { res.sendFile( __dirname + '/signup.html') }); app.post('/', function(req, res) { const FirstName = req.body.firstName const LastName = req.body.lastName console.log(FirstName) console.log(LastName) }); app.listen(port, function(err) { if (err) console.log(err) console.log('Local port started at', port) });
HTML表单代码
<form action="/" method="post"> <label for="firstName">First Name</label> <input class="form-grid__item--field" type="text" id="firstName" placeholder="First Name"> <label for="lastName">Last Name</label> <input class="form-grid__item--field" type="text" id="lastName" placeholder="Last Name"> <label for="subscriberEmail">Email</label> <input class="form-grid__item--field" type="text" id="subscriberEmail" placeholder="Email"> <input type="submit" class="form__button" value="Sign Me Up!"> </form>
问题根源
HTML表单的<input>元素缺少**name属性**。表单提交时,浏览器只会携带带有name属性的字段数据,id属性仅用于关联标签或DOM操作,不会作为表单数据的键名传递。
修复方案
为每个需要提交的<input>添加name属性,属性值与后端req.body中要获取的键名保持一致:
修改后的HTML表单代码:
<form action="/" method="post"> <label for="firstName">First Name</label> <input class="form-grid__item--field" type="text" id="firstName" name="firstName" placeholder="First Name"> <label for="lastName">Last Name</label> <input class="form-grid__item--field" type="text" id="lastName" name="lastName" placeholder="Last Name"> <label for="subscriberEmail">Email</label> <input class="form-grid__item--field" type="text" id="subscriberEmail" name="subscriberEmail" placeholder="Email"> <input type="submit" class="form__button" value="Sign Me Up!"> </form>
验证
重启Express服务后提交表单,后端控制台将正常打印出firstName和lastName的值,req.body不再为空。
内容的提问来源于stack exchange,提问作者Jhoan Trujillo
相关产品推荐
相关产品推荐

