Monday, 1 May 2017

How to structure files / dependencies in multi-files project of NodeJS, ExpressJS with MySql

I'm a beginner in nodejs. I'm trying to build a small project but not to understand the flow. Some error in dependencies is kept on coming even when all these are present in package.JSON and app.js. e.g. : app.post('/title',urlencodedParser, function(req,res,next) { ^ ReferenceError: urlencodedParser is not defined

app.js is where I'm keeping all the dependencies. index.js is going to do all the get/post work. and db.js will do all the query part.

Being a beginner I'm not able to design the project properly in multi-file structure. I'm able to run by keeping everything in app.js but after segregating it starts failing.

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());
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
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 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'));

routs/index.js

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

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


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',urlencodedParser, 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();
  });
 });

 };

views/pages/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>

config/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");
  }
});



via Surya Singh

No comments:

Post a Comment