Node.js中如何获取EJS表单文本字段的输入数据?
在Node.js中获取EJS表单输入数据的方法
没问题,我来帮你搞定这个!既然你用了EJS和Node.js,大概率是搭配Express框架来做的,下面一步步教你怎么获取这个文本字段的输入:
1. 先配置请求体解析中间件
表单提交的POST请求默认是application/x-www-form-urlencoded格式,我们需要让Express能解析这种格式的请求体。
如果你的Express版本是4.16.0及以上,不用额外安装依赖,直接用内置的解析功能:
const express = require('express'); const app = express(); // 关键:解析表单格式的请求体 app.use(express.urlencoded({ extended: true }));
要是你用的是更老的Express版本,得先安装body-parser包:
npm install body-parser
然后引入并配置:
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({ extended: true }));
⚠️ 注意:这个中间件的配置一定要写在所有路由的前面,不然req.body会是undefined!
2. 完善EJS里的表单action
你的表单action属性是空的,得指定一个路由地址,这样提交后请求会发到对应的Node.js路由上。比如我们指定/handle-product-search:
<form action="/handle-product-search" method="POST"> <div class="input-group"> <input type="text" class="form-control" name="userSearchInput" placeholder="Enter the id of the product you would like to buy" aria-label="Recipient's username" aria-describedby="basic-addon2"> <div class="input-group-append"> <button class="btn btn-outline-secondary" id="searchBtn">Submit</button> </div> </div> </form>
3. 编写POST路由获取数据
现在在你的Node.js代码里,写一个对应/handle-product-search的POST路由,通过req.body就能拿到表单输入的数据——注意要和input的name属性(也就是userSearchInput)对应:
app.post('/handle-product-search', (req, res) => { // 从请求体中取出用户输入的产品ID const productId = req.body.userSearchInput; // 这里就可以做你需要的操作了,比如查询数据库、验证ID合法性等 console.log('用户提交的产品ID:', productId); // 举个例子:把数据传给EJS页面渲染结果 res.render('product-result', { targetId: productId }); });
几个关键提醒
- 表单的
method必须是POST,要和路由的app.post()对应 - input的
name属性是核心,req.body的字段名必须和它完全一致,大小写也要注意 - 如果你的表单有文件上传,那得用
multer这类中间件,但你这个是文本输入,上面的方法完全够用
内容的提问来源于stack exchange,提问作者J.G.Sable
相关产品推荐
相关产品推荐

