Не отображает данные на странице - PullRequest
0 голосов
/ 19 июня 2019

Мне нужно отобразить данные из базы данных на странице (/dashboard.hbs). Я нашел код, который его реализует, но он не работает для меня (взял его отсюда https://metanit.com/web/nodejs/8.6.php). Я записал его в server.js, но, как мне кажется, его нужно записать в другом файле. Пожалуйста, помогите мне разобраться, как заставить это работать.

Я уже пытался поместить его в свой auth.js, но это не помогло.

app / config / config.json:

{
"development": {

"username": "root",
"password": "1221",
"database": "nightgl",
"host": "localhost",
"dialect": "mysql"
 },
 "test": {
 "username": "",
 "password": null,
 "database": "",
 "host": "",
 "dialect": "mysql"
  },
 "production": {
 "username": "",
 "password": null,
 "database": "",
"host": "localhost",
"dialect": "mysql"
 }
 }
app/controllers/authcontroller.js :

 var exports = module.exports = {}


 exports.signup = function(req,res){

 res.render('signup'); 
 }

 exports.signin = function(req,res){

    res.render('signin');

   }

    exports.dashboard = function(req,res){

      res.render('dashboard');

     } 

 exports.logout = function(req,res){

  req.session.destroy(function(err) {
  res.redirect('/');
    });

  }


app/models/index.js :

         "use strict";

         var fs        = require("fs");
       var path      = require("path");
      var Sequelize = require("sequelize");
      var env       = process.env.NODE_ENV || "development";
      var config    = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
      var sequelize = new Sequelize(config.database, config.username, config.password, config);
      var db        = {};


        fs
       .readdirSync(__dirname)
       .filter(function(file) {
          return (file.indexOf(".") !== 0) && (file !== "index.js");
        })
        .forEach(function(file) {
         var model = sequelize.import(path.join(__dirname, file));
          db[model.name] = model;
        });

     Object.keys(db).forEach(function(modelName) {
       if ("associate" in db[modelName]) {
        db[modelName].associate(db);
         }
           });


       db.sequelize = sequelize;
       db.Sequelize = Sequelize;

       module.exports = db;

auth.js:

       var authController = require('../controllers/authcontroller.js');

       module.exports = function(app,passport){

       app.get('/signup', authController.signup);


       app.get('/signin', authController.signin);


         app.post('/signup', passport.authenticate('local-signup',  { successRedirect: '/dashboard',
         failureRedirect: '/signup'}
                                                ));


          app.get('/dashboard',isLoggedIn, authController.dashboard);


          app.get('/logout',authController.logout);


          app.post('/signin', passport.authenticate('local-signin',  { successRedirect: '/dashboard',
          failureRedirect: '/signin'}
                                                ));


  function isLoggedIn(req, res, next) {
   if (req.isAuthenticated())
    return next();

   res.redirect('/signin');
}

}

server.js:

var express    = require('express')
var app        = express()
var passport   = require('passport')
var session    = require('express-session')
var bodyParser = require('body-parser')
var env        = require('dotenv').config()
var exphbs     = require('express-handlebars')



//For BodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


 // For Passport
app.use(session({ secret: 'keyboard cat',resave: true, saveUninitialized:true})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions


 //For Handlebars
app.set('views', './app/views')
app.engine('hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');


app.get('/', function(req, res){
  res.send('Welcome to Passport with Sequelize');
});


//Models
var models = require("./app/models");


//Routes
var authRoute = require('./app/routes/auth.js')(app,passport);


//load passport strategies
require('./app/config/passport/passport.js')(passport,models.user);


//Sync Database
models.sequelize.sync().then(function(){
console.log('Nice! Database looks fine')

}).catch(function(err){
console.log(err,"Something went wrong with the Database Update!")
});



app.listen(5000, function(err){
    if(!err)
    console.log("Site is live"); else console.log(err)

});

app.use(express.static('public'));
const mysql = require("mysql2");
const urlencodedParser = bodyParser.urlencoded({extended: false});

const pool = mysql.createPool({
  connectionLimit: 5,
  host: "localhost",
  user: "root",
  database: "nightgl",
  password: "1221"
});


app.set("view engine", "hbs");
 
//
app.get("/dashboard", function(req, res){
    pool.query("SELECT * FROM users", function(err, data) {
      if(err) return console.log(err);
      res.render("dashboard.hbs", {
          users: data
      });
    });
});
// 
app.get("/create", function(req, res){
    res.render("create.hbs");
});

// 
app.post("/create", urlencodedParser, function (req, res) {
         
    if(!req.body) return res.sendStatus(400);
    const name = req.body.name;
    const age = req.body.age;
    pool.query("INSERT INTO users (name, age) VALUES (?,?)", [name, age], function(err, data) {
      if(err) return console.log(err);
      res.redirect("/");
    });
});
 
// 
app.get("/edit/:id", function(req, res){
  const id = req.params.id;
  pool.query("SELECT * FROM users WHERE id=?", [id], function(err, data) {
    if(err) return console.log(err);
     res.render("edit.hbs", {
        user: data[0]
    });
  });
});
// 
app.post("/edit", urlencodedParser, function (req, res) {
         
  if(!req.body) return res.sendStatus(400);
  const name = req.body.name;
  const age = req.body.age;
  const id = req.body.id;
   
  pool.query("UPDATE users SET name=?, age=? WHERE id=?", [name, age, id], function(err, data) {
    if(err) return console.log(err);
    res.redirect("/");
  });
});
 
// 
app.post("/delete/:id", function(req, res){
          
  const id = req.params.id;
  pool.query("DELETE FROM users WHERE id=?", [id], function(err, data) {
    if(err) return console.log(err);
    res.redirect("/");
  });
});

и мой dashboard.hbs:

<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="/css/style.css">
<head>
    <title>database</title>
</head>
<body>
    <div class="site-style">



<div class="fullscreen-bg">
    <div class="main-log1"> <table>
        <tr><th>id</th><th>firstname</th><th>lastname</th><th>username</th><th>about</th><th>email</th><th>password</th><th>last_login</th><th>status</th><th></th></tr>
        {{#each users}}
            <tr>

                <td>{{this.id}}</td>
                <td>{{this.firstname}}</td>
                                <td>{{this.lastname}}</td>
 <td>{{this.username}}</td>
 <td>{{this.about}}</td>
 <td>{{this.email}}</td>
 <td>{{this.password}}</td>
 <td>{{this.last_login}}</td>
 <td>{{this.status}}</td>
 
                <td>
                    <a href="/edit/{{this.id}}">Edit</a>|
                    <form action="delete/{{this.id}}" method="POST" style="display: inline;">
                        <input type="submit" value="Delete" />
                    </form>
                </td>
            </tr>
        {{/each}}
    </table>
 </div>

 <video loop muted autoplay poster="video/plane.jpg" class="fullscreen-bg__video" width="100%" height="auto" autoplay="autoplay" loop="loop" preload="auto">
            <source src="club_v.mp4" type="video/mp4">

    </video>
    </div>

</body>
</html>

Structure_of_project:

image

На странице нет нужных данных.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...