![](/img/trans.png)
[英]How to get data by hitting an url and then rendering it to html using node.js and express.js
[英]Populate html dropdownlist with fetched mysql data using Node.js/Express.js
嘗試使用 Express.js 使用數據填充選擇下拉列表。
項目結構
用戶表
MySQL配置文件
數據庫連接.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;
索引.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;
索引.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>
應用程序.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}`));
運行上面的代碼,我得到這個:
但是,我希望得到這個下拉列表:
要求:
如何從用戶表中獲取 MySQL 數據並顯示在 index.html 下拉列表中?
我期待着這里的幫助,但是,與此同時,我設法將 app.js 文件更改為這個文件並且它起作用了!
'use strict';
const express = require('express');
const path = require('path');// add path module,
const cors = require('cors');
const bodyParser = require('body-parser');
const engine = require('consolidate');
const app = express();
// view engine setup
app.set('views', __dirname+ '/views');
// make server object that contain port property and the value for our server.
//app.engine('html', engine.mustache);
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// routers
const apiRouter = 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('/', apiRouter);
// router user input
app.get('*', function(req, res){
res.render('index.html');
});
const server = {
port: 4040
};
// starting the server
app.listen(server.port, () => console.log(`Server started, listening port: ${server.port}`));
快樂編碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.