如何使用MySql构建NodeJS,ExpressJS的多文件项目中的文件/依赖项

时间:2017-05-01 18:32:34

标签: javascript mysql node.js express

我是nodejs的初学者。我正在尝试建立一个小项目但不了解流程。即使所有这些错误都存在于package.JSON和app.js中,依赖关系中仍会出现一些错误。 e.g。 :ReferenceError:未定义conn

app.js是我保留所有依赖项的地方。 index.js将完成所有的get / post工作。和db.js将完成所有查询部分。

作为初学者,我无法在多文件结构中正确设计项目。我可以通过将所有内容保存在app.js中来运行,但在隔离后它开始失败。

app.js:

var express = require('express');
var app = module.exports = express();
var http = require('http');
var path = require('path');
var mysql = require('mysql');
var passport = require('passport');
var flash    = require('connect-flash');

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

var configDB = require('./config/db.js');
// understand and resolve this
// mysql.connect(configDB.url); // connect to our database

// app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine', 'ejs'); // view engine

// required for passport
app.use(session({ secret: 'tantanatantantantara' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

// var router = express.Router();
var routes = require('./routes/index')(app, passport); // understand and resolve this

http.createServer(app).listen(1337, function(){
  console.log('Movie trailer is running on port ' + 1337);
});


app.set('views', path.join(__dirname, 'views'));
app.use(express.static(__dirname + '/public'));

路由/ index.js

var express = require('express');
var router = express.Router();

module.exports = function(app) {


app.get('/',function(req,res){
    res.render('pages/index',{
      qStr: req.query
    });
});

app.get('/title',function(req,res){
  res.render('pages/title');
});

app.post('/title', function(req,res,next) {
  var key = req.body.title;
  // console.log("key"+JSON.stringify(req.body));
  var queryString = "SELECT * FROM data where title like '%"+key+"%'";
  conn.query(String(queryString),function (err,rows) {
    if (err) throw err;
    var name = rows[0].Title,
        year = rows[0].Year,
        rating = rows[0].Rated,
        releas = rows[0].Released,
        dur = rows[0].Runtime,
        genre = rows[0].Genre,
        director = rows[0].Director,
        writer = rows[0].Writer,
        actors = rows[0].Actors,
        plot = rows[0].Plot,
        lang = rows[0].Language,
        awards = rows[0].Awards,
        poster = rows[0].Poster,
        imdbR = rows[0].imdbRating,
        imdbVotes = rows[0].imdbVotes;
    // console.log(rows);
      // res.write(name);
      res.render('pages/title',{
        name:name.toString(),
        plot:plot.toString(),
        image_link:poster.toString()
      });
        res.end();
  });
 });

 };

视图/页/ index.ejs

<html lang="en">
  <% include ../partials/header %>
  <body>
    <% include ../partials/nav %>
    <section name="search-area">
                <div class="search-row text-center">
                  <form method="POST" action="/title">
                  <input type="search" placeholder="Search movies" name="title" value="<%= qStr.name %>" class="search-input">
                  <input type="submit" class="search-button" value="Submit">
                  </form>
                </div>
      </section>

<% include ../partials/footer %>
<% include ../partials/scripts %>
</body>
</html>

配置/ db.js

var mysql = require('mysql');

var conn = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'movie_trailers'
});

conn.connect(function(error) {
  if (err) {
    console.log("Error");
  } else {
    console.log("Connected");
  }
});

0 个答案:

没有答案