首先,对于Node和express来说是非常新的东西。我正在尝试使用两个不同的查询结果填充两个下拉列表。例如,我想要两个下拉菜单,一个为date
,另一个为name
。
我尝试为date
做一个下拉菜单,它工作得很好。但是,当我尝试同时执行这两个操作时,请继续出现此错误:names is not defined
。
Router.js
const express = require('express')
const router = express.Router()
const { conn } = require('./config')
router.get('/', async (req, res) => {
try {
var dates = conn.query('select date from table', function(req, result){
console.log(result);
res.render('index', {dates : result});
});
} catch (err) {
res.status(500)
res.send(err.message)
}
});
router.get('/', async (req, res) => {
try {
var names = conn.query('select name from table2', function(req, result){
console.log(result);
res.render('index', {names : result});
});
} catch (err) {
res.status(500)
res.send(err.message)
}
});
Index.ejs
<div class="Date_Dropdown">
<span class="caret"></span></button>
<ul class="dropdown-menu">
<% for(var i=0; i < dates.recordset.length; i++) { %>
<li><%= dates.recordset[i].Date%></li>
<% } %>
</ul>
</div>
<div class="Name_Dropdown">
<span class="caret"></span></button>
<ul class="dropdown-menu">
<% for(var n=0; n < names.recordset.length; n++) { %>
<li><%= names.recordset[n].Name%></li>
<% } %>
</ul>
</div>
App.js
app.use('/', router);
我试图实现两个下拉菜单,一个用于日期,一个用于名称,并且不断抛出此错误:
names is not defined
at eval (eval at compile (), <anonymous>:20:25)
at returnedFn ()
at tryHandleCache ()
at View.exports.renderFile [as engine] (Desktop\Node\node_modules\ejs\lib\ejs.js:482:10)
at View.render (Desktop\Node\node_modules\express\lib\view.js:135:8)
at tryRender (Desktop\Node\node_modules\express\lib\application.js:640:10)
at Function.render (Desktop\Node\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (Desktop\Node\node_modules\express\lib\response.js:1008:7)
at Desktop\Node\model\router.js:25:13
at _query (Desktop\Node\node_modules\mssql\lib\base.js:1347:9)
答案 0 :(得分:1)
两个处理同一条/
路由的函数将不起作用。里面只有一个
...
try {
var dates = await conn.query('select date from table');
var names = await conn.query('select name from table2')'
res.render( 'index', {dates : dates, names: names} );
}