0 996
使用 node.js 和 express.js 读取 html 表单输入_图一

我正在尝试从 HTML 表单中读取输入并在 Node.js 中使用它。

这是我的 HTML 表单:

<form action="/myform" method="POST">
     <input type="text" name="mytext" required />
     <input type="submit" value="Submit" />
</form>
这是我的 Node.js 代码:


app.post('/myform', function(req, res){ 
  console.log(req.body.mytext); //mytext is the name of your input box
});
我收到此错误:


TypeError: Cannot read properties of undefined (reading 'mytext')   
Please help me out.

正确解答

确保您正在解析请求。为此,在服务器根文件的顶部添加以下行:


app.use(express.urlencoded({
  extended: true
}));


普通的 HTML 表单不会发送 JSON。 

它现在只是在控制台中打印“未定义”。 

[分类]
[来源] https://stackoverflow.com/questions/71347744/reading-html-form-input-with-with-node-js-and-express-js
[声明] 本站资源来自用户分享,如损害你的权益请联系客服QQ:120074275给予处理。