我试图通过在express中调用API来显示SQL查询的结果,但不显示结果。我可以在控制台中将它们视为数据包的数组,但无法显示它们。
var express = require('express');
var router = express.Router();
var passport = require ('passport');
var bcrypt = require('bcrypt');
const saltRounds = 10;
const mysql = require ('mysql');
const path = require('path')
const hbs = require('hbs');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var { check, validationResult } = require('express-validator/check');
router.use(bodyParser.json());
// most of body code omitted
router.get('/tableResults',(req, res) => {
console.log(req.session.passport.user);
const db = require('./db_connection.js');
var id = req.session.passport.user;
db.query('SELECT * FROM testResults where id = ?',[id],function(error, results, fields) { // results are displayed where the user ids match
if(error) throw error;
// JSON.parse(JSON.
console.log(results);
if ( results = null ) {
res.redirect('/home');
};
res.render('tableResults',{
results: results
});
});
});
<html lang="en"> // the correspontiong .hbs page to be rendered with results
<head>
<meta charset="utf-8">
<title>Test Results</title>
</head>
<body>
<div class="container">
<h2>Test Results</h2>
<button class="btn btn-success" data-toggle="modal" data-target="#testResults">Add New</button>
<table class="table table-striped" id="mytable">
<thead>
<tr>
<td> Test id</td>
<th>Grade 1s</th>
<th>Grade 2</th>
<th>G3</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{{#each results}}
<tr>
<td>{{ test_id: results }}</td>
<td>{{ gradeOne }}</td>
<td>{{ gradeTwo }}</td>
<td>{{ gradeThree }}</td>
<td>
<a href="javascript:void(0);" class="btn btn-sm btn-info
edit" data-id="{{ test_id }}" data-grade-one="{{ gradeOne }}" data-
grade-two="{{ gradeTwo }}" data-grade-three="{{ gradeThree }}>Edit
</a>
<a href="javascript:void(0);" class="btn btn-sm btn-danger
delete" data-id="{{ test_id }}">Delete</a>
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
我不知道为什么我无法在页面上看到结果,因为数据在控制台中。我的layout.hbs
页面中也链接了jQuery CDN
答案 0 :(得分:1)
在代码if ( results = null ) {...}
中,您正在使用results
值重新分配null
(值是赋值运算符)。您的console.log
就在您重新分配之前。
代替使用equality operator
if ( results == null ) {
res.redirect('/home');
};