如何在EJS文件中使用MySQL进行查询

时间:2017-06-01 08:29:40

标签: javascript sql node.js

我正在尝试在视图(.ejs文件)中运行查询。但是,由于关键字require没有在.ejs文件中定义,我需要从我的主文件server.js中导出它。

我的server.js文件的完整代码如下所示,这是我需要帮助的特定代码段。

app.engine('html',require('ejs')。renderFile);

exports.profile = function(req,res){

res.render('profile',{mysql:mysql}); }

我需要能够在我的profile.ejs文件中使用mysql.createConnection。

任何帮助都会很棒。

// server.js

// set up ======================================================================
// get all the tools we need
var express  = require('express');
var app      = express();
var port     = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');

var morgan       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');
var session      = require('express-session');

var configDB = require('./config/database.js');
var Connection = require('tedious').Connection;
var config = {
userName: 'DESKTOP-S6CM9A9\\Yash',
password: '',
server: 'DESKTOP-S6CM9A9\\SQLEXPRESS',
};
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;

  var mysql = require('mysql');
  var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "yashm"
  });

 con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql="Select * from test.productlist";
con.query(sql, function (err, result) {
  if (err) throw err;
  console.log(result);
});
});

app.engine('html', require('ejs').renderFile);


exports.profile = function(req, res) {
    res.render('profile', { mysql: mysql });
}



//--------------------------------------------------------------------------------




// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating

// required for passport
app.use(session({ secret: 'test run' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);

1 个答案:

答案 0 :(得分:1)

就像在评论中已经说过的那样,你必须在server.js中执行查询逻辑,然后将数据传递给你的视图(或者甚至可以预处理它!)

exports.profile = function(req, res) {
    con.query('SELECT 1', function (error, results, fields) {
      if (error) throw error;
      // connected!
      res.render('profile', { data: results });
    });
}

在您的ejs中,您可以循环播放数据,并以数据[i] [' fieldname']

的形式访问字段
<ul>
<% for(var i=0; i<data.length; i++) {%>
   <li><%= data[i]['id'] %></li>
<% } %>
</ul>