如何通过HTML按钮调用Node.js+MongoDB的find()查询并展示结果?
以下是实现你需求的具体步骤和代码示例:
一、先修正原有路由的语法错误
你原来的User.find调用存在语法错误,回调函数应作为第二个参数传入,修正后的根路由代码:
app.get('/', (req, res) => { User.find({ firstName: 'vinicius' }, (err, users) => { if (err) return res.status(500).send('查询出错'); res.render('index', { userList: users }); }); });
二、新增后端路由
1. 查询所有用户的路由
添加一个GET路由用于返回所有用户数据:
app.get('/all-users', (req, res) => { User.find({}, (err, users) => { if (err) return res.status(500).send('查询出错'); res.render('index', { userList: users }); }); });
2. 根据CPF查询用户的路由
添加接收CPF参数的GET路由(确保你的User模型包含cpf字段):
app.get('/user-by-cpf', (req, res) => { const cpf = req.query.cpf; if (!cpf) return res.status(400).send('请输入CPF'); User.find({ cpf: cpf }, (err, users) => { if (err) return res.status(500).send('查询出错'); res.render('index', { userList: users }); }); });
三、改造EJS前端页面
更新模板,添加查询控件并优化数据渲染逻辑:
<!-- 查询操作区域 --> <div> <!-- CPF查询表单 --> <form action="/user-by-cpf" method="GET"> <input type="text" name="cpf" placeholder="输入CPF查询" required> <button type="submit">按CPF查询</button> </form> <!-- 查询所有用户按钮 --> <a href="/all-users"><button>查询所有用户</button></a> </div> <!-- 用户列表展示区域 --> <div> <% if (userList && userList.length > 0) { %> <% userList.forEach(user => { %> <p><%= user.firstName %> - <%= user.cpf %></p> <% }) %> <% } else { %> <p>暂无用户数据</p> <% } %> </div>
可选:无刷新查询(AJAX方式)
如果不想刷新页面,可通过JavaScript发送AJAX请求更新内容:
<!-- 无刷新查询区域 --> <div> <input type="text" id="cpfInput" placeholder="输入CPF查询"> <button id="queryCpfBtn">按CPF查询</button> <button id="queryAllBtn">查询所有用户</button> </div> <div id="userList"></div> <script> // 按CPF查询 document.getElementById('queryCpfBtn').addEventListener('click', () => { const cpf = document.getElementById('cpfInput').value; if (!cpf) { alert('请输入CPF'); return; } fetch(`/user-by-cpf-json?cpf=${cpf}`) .then(res => res.json()) .then(result => { let html = ''; if (result.success) { html = result.data.length > 0 ? result.data.map(user => `<p>${user.firstName} - ${user.cpf}</p>`).join('') : '<p>未找到该CPF对应的用户</p>'; } else { html = `<p>查询失败:${result.message}</p>`; } document.getElementById('userList').innerHTML = html; }) .catch(err => console.error('查询出错:', err)); }); // 查询所有用户 document.getElementById('queryAllBtn').addEventListener('click', () => { fetch('/all-users-json') .then(res => res.json()) .then(result => { let html = ''; if (result.success) { html = result.data.length > 0 ? result.data.map(user => `<p>${user.firstName} - ${user.cpf}</p>`).join('') : '<p>暂无用户数据</p>'; } else { html = `<p>查询失败:${result.message}</p>`; } document.getElementById('userList').innerHTML = html; }) .catch(err => console.error('查询出错:', err)); }); </script>
对应需新增返回JSON格式的后端路由:
// 返回JSON的所有用户路由 app.get('/all-users-json', (req, res) => { User.find({}, (err, users) => { if (err) return res.status(500).json({ success: false, message: '查询出错' }); res.json({ success: true, data: users }); }); }); // 返回JSON的CPF查询路由 app.get('/user-by-cpf-json', (req, res) => { const cpf = req.query.cpf; if (!cpf) return res.status(400).json({ success: false, message: '请输入CPF' }); User.find({ cpf: cpf }, (err, users) => { if (err) return res.status(500).json({ success: false, message: '查询出错' }); res.json({ success: true, data: users }); }); });
内容的提问来源于stack exchange,提问作者vinicius souza
相关产品推荐
相关产品推荐

