使用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.
I am trying to read the input from an HTML form and use it in Node.js.
This is my HTML form:
<form action="/myform" method="POST">
<input type="text" name="mytext" required />
<input type="submit" value="Submit" />
</form>
This is my Node.js code:
app.post('/myform', function(req, res){
console.log(req.body.mytext); //mytext is the name of your input box
});
I am getting this error:
TypeError: Cannot read properties of undefined (reading 'mytext')
Please help me out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保您正在解析请求。为此,请在服务器根文件的顶部添加以下行:
Make sure you are parsing the request. For that, add the line below at the top of your server root file:
您必须使用内置方法express.json()来解析json数据。
要使用此方法,您需要中间件 app.use()
因此,您必须像下面一样定义它,但在主文件中定义任何路由之前。
应用程序.use(express.json())
You have to used a inbuilt method express.json() for parsing json data.
To used this method you need middlewares app.use()
So you have to defined it like below but before defining any routes in main file.
app.use(express.json())
我遇到了同样的问题,您需要可以像这样安装的主体解析器中间件
然后将其包含在您的服务器文件中
并在服务器顶部添加以下内容
请请注意,此模块不处理多部分机构,由于其复杂且通常较大的性质。
I had this same problem, you need the body parser middleware which can be installed like so
Then include it in your server file
And add the following at the top of your server
Please note that this module does not handle multipart bodies, due to their complex and typically large nature.