【问题标题】:Populate html dropdownlist with fetched mysql data using Node.js/Express.js使用 Node.js/Express.js 使用获取的 mysql 数据填充 html 下拉列表
【发布时间】: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


    【解决方案1】:

    我期待从这里得到帮助,但是,与此同时,我设法将 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}`));
    

    愉快的编码

    【讨论】:

      猜你喜欢
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多