【发布时间】:2023-04-02 21:20:01
【问题描述】:
尝试使用 Express.js 使用数据填充选择下拉列表。
项目结构
用户表
MySQL 配置文件
dbConnection.js
const mysql = require('mysql');
var dbConnection = mysql.createConnection({
host: 'localhost', // database host
user: 'horation', // your database username
password: 'hmsvictory', // your database password
port: 3306, // default MySQL port
db: 'display_images' // your database name
});
dbConnection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL Server!');
});
module.exports = dbConnection;
index.js
'use strict';
var express = require('express');
var router = express.Router();
var _sql = require("mysql");
var myConnection = require('express-myconnection');
var _config = require('../DataStore/dbConnection');
var dbOptions = {
host: _config.host,
user: _config.user,
password: _config.password,
database: _config.db
}
app.use(myConnection(_sql, dbOptions, 'pool'));
/* GET home page. */
router.get('/', function (req, res) {
_sql.connect(_config.dbConnection()).then(() => {
return _sql.query`SELECT name FROM studentinfo`
}).then(result => {
console.log(result);
// Pass the DB result to the template
res.render('/index', {dropdownVals: result.recordset});
}).catch(err => {
console.log(err)
})
});
module.exports = router;
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>Binding MySQL data to a DropDownList</h1>
<label>Name: </label>
<select>
<% for (const i in dropdownVals) { %>
<option value="<%= dropdownVals[i].id %>"> <%= dropdownVals[i].name %> </option>
<% } %>
</select>
</body>
</html>
app.js
const express = require('express'),
path = require('path') // add path module,
app = express(),
cors = require('cors'),
bodyParser = require('body-parser');
// make server object that contain port property and the value for our server.
var server = {
port: 4040
};
// routers
const router = require('./routes/index');
// use the modules
app.use(cors())
app.use(bodyParser.json());
app.use(express.json())
app.use(express.urlencoded({extended: true})) // parsing incoming requests with urlencoded based body-parser
// use router
app.use('/index', router);
// router user input
app.get('/', function(req, res) {
res.sendFile(path.resolve(__dirname,'views') + '/index.html');
});
// starting the server
app.listen( server.port, () => console.log(`Server started, listening port: ${server.port}`));
运行上面的代码,我得到了这个:
但是,我希望得到这个下拉列表:
必填:
如何从 users 表中获取 MySQL 数据并显示在 index.html 下拉列表中?
【问题讨论】:
标签: javascript html mysql node.js express