javascript - 使用 Node.js 从 MySQL 获取数据并显示在索引页面上
问题描述
每当我在浏览器上运行我的网站时,我都会收到以下错误消息:http://localhost:3000
. 我正在努力解决这个问题。有没有其他方法或更好的方法从 MySQL 获取数据并使用 Node.js 将其显示在我的索引页面上?
错误
Error: Failed to lookup view "index" in views directory "C:\test\views"
索引.ejs
<!DOCTYPE html>
<html>
<head>
<title>MySQL Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<table id="tblData" class="table table-bordered table-hover">
<thead class="thead-inverse">
<tr>
<th data-column-id="Name">
Name
</th>
<th data-column-id="Message">
Message
</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
//Declare the var with the data
var Result = <%- JSON.stringify(result) %>;
var TableData = null;
$(function () {
function ajusTables() {
$('.table').css('width', '100%');
$('.dataTables_scrollHeadInner').css('width', '100%');
}
TableData = $('#tblData').DataTable({
"serverSide": false,
"drawCallback": function (settings) {
ajusTables();
},
"scrollX": true,
"processing": true,
"paging": true,
"lengthChange": false,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"deferRender": true,
"columns": [
{ "data": "Name" },
{ "data": "Message" },
],
"order": [0, "asc"]
});
console.log(Result);
TableData.rows.add(Result)
TableData.draw();
});
</script>
</body>
</html>
我安装了 EJS 包,在 html 中使用 Javascript 并从后端处理数据。
将res.render("Index", {result: result});
调用 Index.ejs 传递带有数据的 JSON。
应用程序.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', express.static(__dirname + '/'));
app.set("view engine", "ejs");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
connection.connect();
app.get('/', function (req, res) {
connection.query('SELECT * FROM chat', function(err, result, fields) {
connection.end();
if (err) throw err;
console.log("Data displayed");
res.render("index", { result: result });
});
});
app.listen(3000, function () {
console.log('Connected to port 3000');
});
解决方案
参考链接:https ://www.codementor.io/naeemshaikh27/node-with-express-and-ejs-du107lnk6
请在视图文件夹中创建index.ejs 。
推荐阅读
- android - 如何在 Android Studio 上对齐屏幕底部的按钮
- elasticsearch - 搜索与解释中的弹性分数不同
- javascript - 在不使用 DOM 解析器的情况下将 Html 字符串解析为特定数组
- javascript - 为命令运行多个文件夹
- wordpress - 覆盖插件function.php
- jmeter - JMeter API 负载测试 - 404 响应代码 = 测试失败?
- c# - 在不使用其他项目的情况下添加 Entity Framework 核心迁移
- python-3.x - 有没有办法在 print 语句中使用 for 循环?
- react-native - 启动远程调试后无法使用该应用程序
- grafana - Influxql 使用 distinct 函数显示所有字段