出现req.body.[input的名称]变为undefined的问题通常是由于未正确配置和使用表单提交中间件造成的。以下是一个解决方法的代码示例:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 使用body-parser中间件解析表单数据
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/submit', (req, res) => {
// 在这里可以使用req.body.[input的名称]来访问表单提交的数据
console.log(req.body);
res.send('表单提交成功!');
});
app.listen(3000, () => {
console.log('服务器已启动');
});
在上述示例中,我们使用了express框架和body-parser中间件来解析表单数据。在服务器端,通过req.body来访问表单提交的数据,确保在表单中的input元素上添加了正确的name属性。这样,当表单提交时,req.body中的属性将会被正确地填充。