如何将mysql数据库内容传递到其他页面?

s71maibg  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(377)

我正在尝试将我的数据库内容显示到ejs网页。但是,我在尝试在页面之间传递内容时遇到了一个问题。
我有一个javascript页面 "store.js" 使服务器运行:
商店.js-

var express = require('express');
var dbcon = require('./app/db/databaseconnection');
//var path = require('path');
//dbcon.connection;

var app = express();
var router = express.Router();

dbcon.connect();
console.log(dbcon.getproducts());

//var filepath = path.join(__dirname, '../../views/')
var filepath = __dirname + '/views/';
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use('/', router);

router.get('/', (request, response) => response.render(filepath + 'index', { page_name: 'home' }));
router.get('/store', (request, response) => response.render(filepath + 'store', { page_name: 'store' }));
router.get('/about', (request, response) => response.render(filepath + 'about', { page_name: 'about' }));
router.get('/contact', (request, response) => response.render(filepath + 'contact', { page_name: 'contact' }));
router.get('/build', (request, response) => response.render(filepath + 'build/build'));
router.get('/learn', (request, response) => response.render(filepath + 'learn/learn'));
app.use('*', (request, response) => response.render(filepath + '404', { page_name: '404' }));
app.listen(3000, () => console.log("Server running at Port 3000"));

然后我有一个包含数据库连接的javascript页面:
数据库连接.js-

var mysql = require('mysql');
var connection = mysql.createConnection(conObject = {
    host: "localhost",
    user: "root",
    password: "LOTOS123l",
    database: "dbComputerStore"
});

module.exports = {
    connect: () => 
    { 
        connection.connect((error) => {
            if (error) throw error;
            console.log(conObject.database + " connected!");
        });
    },
    // The display method prints the returned result to the console.
    // Change this to return the result. Maybe a toString() ?
    getproducts: () => {
        /*var result = */connection.query('SELECT * FROM products', (error, result) => { 
            return result;
            //return result;
            // console.log(result);
            // How to get certain properties
            // console.log(result[0].brand);
            // console.log(result[0].series);
            // console.log(result[0].model);
        });
        //return result.result;
    },
    createdb: () => {

    },
    createtable: () => {

    },
    populatetable: () => {

    }
}

所以在电视上 store.js 第页我有 console.log(dbcon.getproducts()); 我希望它能显示 "products" table。然而,我一直没有定义。基本上,我无法让它从数据库连接页传递到store.js页。
如果我能实现这个功能,我的下一步将是找到一种将products表显示到ejs页面的方法。我已经尝试解决这个问题有一段时间了,所以任何帮助都将不胜感激!谢谢您!

bvuwiixz

bvuwiixz1#

在我的评论之后,下面是如何修改databaseconnection.js模块以使用连接池并通过承诺返回查询结果:
注意:代码大多未经测试

const mysql = require("mysql");

const pool = mysql.createPool({
  connectionLimit: 10, // adjust this according to your needs
  host: "localhost",
  user: "root",
  password: "LOTOS123l",
  database: "dbComputerStore"
});

module.exports = {
  // you don't need the connect method anymore

  getProducts: () => new Promise((resolve, reject) => {
    pool.query("SELECT * FROM products", (error, results, fields) => {
      if (error) {
        reject(error);
      } else {
        resolve(results);
      }
    });
  }),
  // ...
};

然后在store.js中,您可以执行以下操作:

const dbcon = require('./app/db/databaseconnection');

dbcon.getProducts()
  .then(results => {
    console.log(results);
  })
  .catch(err => {
    console.error(err);
  });

// or you could use async/await syntax:

const asyncFn = async () => {
  try {
    const results = await dbcon.getProducts();
    console.log(results);
  } catch (ex) {
    console.error(err);
  }
};
asyncFn();

相关问题