每当我在浏览器上运行我的网站时,我都会收到以下错误消息:http://localhost:3000
。我正在努力解决这个问题。有没有其他方法或更好的方法从MySQL获取数据并使用Node.js在我的索引页面上显示它?
错误
Error: Failed to lookup view "index" in views directory "C:\test\views"
index.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。
app.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');
});
答案 0 :(得分:1)
参考链接:https://www.codementor.io/naeemshaikh27/node-with-express-and-ejs-du107lnk6
请在观看次数文件夹中创建 index.ejs 。
答案 1 :(得分:0)
检查以确保文件名为index.ejs
而不是Index.ejs
(案例)。