首页 > 解决方案 > 无法在 hbs 中显示 MySql 记录

问题描述

我试图在我的 hbs 页面上显示 MySql 记录,nodejs 既没有得到任何错误也没有结果。我正在使用快速生成器,很长一段时间后我正在编程我已经完成在 MySsql 表中插入数据我的下一步是在 hbs 页面上显示我现在放弃的数据我需要你们的帮助让我知道我的问题在哪里代码?谢谢。

index.js

const { response } = require('express');
var express = require('express');
var router = express.Router();
var mysql = require('mysql')

//SQL connection
var conn = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'MyDatabaseforMyProjects@',
  database: 'crud_db'
})
conn.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
  if (err) throw err
  console.log('Connected to MySQL..')

})


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});

// create page route
router.get('/create', function(req, res, next) {
  res.render('create');
  console.log(req.body)
});

// create page route
router.post('/create', function(req, res, next) {
  
  let data = {
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    email : req.body.email,
    password: req.body.password,
    phone: req.body.phone,
  };
 conn.query(`INSERT INTO user_form set ?`, [data], function(err, result){
   if(err) {console.log(err)}
   else{
      return res.redirect('/');
   } 
 } )
});

// this script to fetch data from MySQL databse table
router.post('/', function(req, res, next) {
  conn.query('SELECT * FROM user_form', function (err, result, data) {
  if (err) throw err;
  
//  return res.redirect('/');
});
});


module.exports = router;


索引.hbs


<h3 class="text-center border border-light p-5 container col-sm-5">User's Record</h3>

<div class=" container col-sm-6"> Click <a href="/create">here</a> to Register user</div>

<table class="table container col-sm-8">
  <thead class="thead-dark">
    <tr>
      <th scope="col">#</th>
      <th scope="col">First name</th>
      <th scope="col">Last name</th>
      <th scope="col">Email</th>
      <th scope="col">Password</th>
      <th scope="col">Phone</th>
      <th scope="col">Action</th>
    </tr>

  <tbody>
         {{#each }}
        <tr>
          <td scope="col">{{ id }}</td>
          <td scope="col">{{ first_name }}</td>
          <td scope="col">{{ last_name }}</td>
          <td scope="col">{{ email }}</td>
          <td scope="col">{{ password }}</td>
          <td scope="col">{{ phone }}</td>

          
        </tr>
        {{/each}}
      </tbody>
 
  
  </thead>

  




标签: javascriptmysqlnode.jsexpresscrud

解决方案


推荐阅读