var fs = require('fs'); var ejs = require('ejs'); var mysql = require('mysql'); var express = require('express'); var bodyParser = require('body-parser'); // 连接mysql数据库 var client = mysql.createConnection({ host: 'localhost', port:"3306", user: 'root', password: 'root123', database: 'my_db_1' }); // //判断是否连接成功 client.connect(function(err){ if(err){ console.log('[query] - :'+err); return; } console.log('[connection connect] Mysql数据库连接成功!'); }); // 解析请求体中的URL的编码数据 var app = express(); app.use(bodyParser.urlencoded({ extended: false })); // app.listen(52273, function () { console.log('服务器运行在 http://127.0.0.1:52273'); }); // app.get('/', function (request, response) { // fs.readFile('book-list.html', 'utf8', function (error, data) { // client.query('SELECT * FROM books', function (error, results) { // response.send(ejs.render(data, { data: results })); }); }); }); // app.get('/delete/:id', function (request, response) { // client.query('DELETE FROM books WHERE id=?', [request.params.id], function () { // response.redirect('/'); }); }); // app.get('/insert', function (request, response) { // fs.readFile('book-insert.html', 'utf8', function (error, data) { // response.send(data); }); }); // app.post('/insert', function (request, response) { // var body = request.body; // client.query('INSERT INTO books (bookname, author, press) VALUES (?, ?, ?)', [ body.bookname, body.author, body.press ], function () { // response.redirect('/'); }); }); // app.get('/edit/:id', function (request, response) { // fs.readFile('book-edit.html', 'utf8', function (error, data) { // client.query('SELECT * FROM books WHERE id = ?', [ request.params.id ], function (error, result) { // response.send(ejs.render(data, { data: result[0] })); }); }); }); // app.post('/edit/:id', function (request, response) { // var body = request.body; // client.query('UPDATE books SET bookname=?, author=?, press=? WHERE id=?', [body.bookname, body.author, body.press, request.params.id], function () { // response.redirect('/'); }); });(2) 理解ejs.render()方法,说出在代码中如何完成向ejs模板文件中动态地渲染数据。
时间: 2024-02-06 13:03:28 浏览: 114
ejs.render()方法用于将数据动态渲染到ejs模板文件中,返回渲染后的html字符串。在上面的代码中,通过读取book-list.html、book-insert.html、book-edit.html等模板文件,并使用ejs.render()方法将查询到的数据库数据动态渲染到模板中,最后返回渲染后的html字符串,响应给客户端浏览器。具体实现方式是在ejs模板文件中使用ejs语法,如<%= data.id %>表示将data对象中的id属性的值动态渲染到模板中。在代码中,使用response.send()方法响应渲染后的html字符串,将数据呈现在浏览器中。
相关问题
var fs = require('fs'); var ejs = require('ejs'); var mysql = require('mysql'); var express = require('express'); var bodyParser = require('body-parser'); // 连接mysql数据库 var client = mysql.createConnection({ host: 'localhost', port:"3306", user: 'root', password: 'root123', database: 'my_db_1' }); // //判断是否连接成功 client.connect(function(err){ if(err){ console.log('[query] - :'+err); return; } console.log('[connection connect] Mysql数据库连接成功!'); }); // 解析请求体中的URL的编码数据 var app = express(); app.use(bodyParser.urlencoded({ extended: false })); // app.listen(52273, function () { console.log('服务器运行在 http://127.0.0.1:52273'); }); // app.get('/', function (request, response) { // fs.readFile('book-list.html', 'utf8', function (error, data) { // client.query('SELECT * FROM books', function (error, results) { // response.send(ejs.render(data, { data: results })); }); }); }); // app.get('/delete/:id', function (request, response) { // client.query('DELETE FROM books WHERE id=?', [request.params.id], function () { // response.redirect('/'); }); }); // app.get('/insert', function (request, response) { // fs.readFile('book-insert.html', 'utf8', function (error, data) { // response.send(data); }); }); // app.post('/insert', function (request, response) { // var body = request.body; // client.query('INSERT INTO books (bookname, author, press) VALUES (?, ?, ?)', [ body.bookname, body.author, body.press ], function () { // response.redirect('/'); }); }); // app.get('/edit/:id', function (request, response) { // fs.readFile('book-edit.html', 'utf8', function (error, data) { // client.query('SELECT * FROM books WHERE id = ?', [ request.params.id ], function (error, result) { // response.send(ejs.render(data, { data: result[0] })); }); }); }); // app.post('/edit/:id', function (request, response) { // var body = request.body; // client.query('UPDATE books SET bookname=?, author=?, press=? WHERE id=?', [body.bookname, body.author, body.press, request.params.id], function () { // response.redirect('/'); }); });补全注释
这段代码是一个使用Node.js搭建的服务器,主要功能是连接MySQL数据库,并通过Express框架提供HTTP服务。以下是代码注释的补全:
```javascript
var fs = require('fs');
var ejs = require('ejs');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
// 连接mysql数据库
var client = mysql.createConnection({
host: 'localhost',
port:"3306",
user: 'root',
password: 'root123',
database: 'my_db_1'
});
// 判断是否连接成功
client.connect(function(err){
if(err){
console.log('[query] - :' + err);
return;
}
console.log('[connection connect] Mysql数据库连接成功!');
});
// 解析请求体中的URL的编码数据
var app = express();
app.use(bodyParser.urlencoded({
extended: false
}));
// 启动服务器
app.listen(52273, function () {
console.log('服务器运行在 http://127.0.0.1:52273');
});
// 处理根路径的GET请求
app.get('/', function (request, response) {
fs.readFile('book-list.html', 'utf8', function (error, data) {
// 查询数据库并将结果渲染到模板中
client.query('SELECT * FROM books', function (error, results) {
response.send(ejs.render(data, {
data: results
}));
});
});
});
// 处理删除图书的GET请求
app.get('/delete/:id', function (request, response) {
client.query('DELETE FROM books WHERE id=?', [request.params.id], function () {
response.redirect('/');
});
});
// 处理插入图书的GET请求
app.get('/insert', function (request, response) {
fs.readFile('book-insert.html', 'utf8', function (error, data) {
response.send(data);
});
});
// 处理插入图书的POST请求
app.post('/insert', function (request, response) {
var body = request.body;
client.query('INSERT INTO books (bookname, author, press) VALUES (?, ?, ?)', [
body.bookname, body.author, body.press
], function () {
response.redirect('/');
});
});
// 处理编辑图书的GET请求
app.get('/edit/:id', function (request, response) {
fs.readFile('book-edit.html', 'utf8', function (error, data) {
client.query('SELECT * FROM books WHERE id = ?', [
request.params.id
], function (error, result) {
response.send(ejs.render(data, {
data: result[0]
}));
});
});
});
// 处理编辑图书的POST请求
app.post('/edit/:id', function (request, response) {
var body = request.body;
client.query('UPDATE books SET bookname=?, author=?, press=? WHERE id=?', [
body.bookname, body.author, body.press, request.params.id
], function () {
response.redirect('/');
});
});
```
Nodejs+express+ejs分页查询
以下是一个基于 Nodejs、Express 和 EJS 的分页查询实现示例:
首先,安装必要的依赖:
```
npm install express ejs mongoose express-flash express-session
```
然后,创建一个名为 `app.js` 的文件,引入所需模块:
```javascript
const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const flash = require('express-flash');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;
// 连接 MongoDB 数据库
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
// 定义数据库模型
const Article = mongoose.model('Article', {
title: String,
content: String,
created_at: Date
});
// 设置模板引擎和静态文件目录
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
// 设置 session 和 flash
app.use(session({
secret: 'mysecretkey',
resave: true,
saveUninitialized: true
}));
app.use(flash());
// 设置 bodyParser
app.use(bodyParser.urlencoded({ extended: true }));
// 定义路由
app.get('/', async function(req, res) {
const perPage = 5;
const page = req.query.page || 1;
const articles = await Article.find()
.skip((perPage * page) - perPage)
.limit(perPage);
const count = await Article.countDocuments();
const totalPages = Math.ceil(count / perPage);
res.render('index', {
articles: articles,
current: page,
pages: totalPages
});
});
app.listen(port, function() {
console.log('Server listening on port ' + port);
});
```
在 `views` 文件夹中创建一个名为 `index.ejs` 的文件,用于显示分页数据:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>分页查询</title>
</head>
<body>
<h1>文章列表</h1>
<% if (articles.length > 0) { %>
<ul>
<% articles.forEach(function(article) { %>
<li><%= article.title %></li>
<% }); %>
</ul>
<% } else { %>
<p>没有文章。</p>
<% } %>
<% if (pages > 1) { %>
<div class="pagination">
<ul>
<% if (current == 1) { %>
<li class="disabled"><span>«</span></li>
<% } else { %>
<li><a href="?page=<%= current - 1 %>">«</a></li>
<% } %>
<% for (var i = 1; i <= pages; i++) { %>
<% if (i == current) { %>
<li class="active"><span><%= i %></span></li>
<% } else { %>
<li><a href="?page=<%= i %>"><%= i %></a></li>
<% } %>
<% } %>
<% if (current == pages) { %>
<li class="disabled"><span>»</span></li>
<% } else { %>
<li><a href="?page=<%= current + 1 %>">»</a></li>
<% } %>
</ul>
</div>
<% } %>
</body>
</html>
```
在上面的示例中,我们使用了 `mongoose` 连接 MongoDB 数据库,并定义了一个名为 `Article` 的数据库模型。在路由中,我们使用 `await` 关键字来等待查询结果,并通过 `skip()` 和 `limit()` 方法来实现分页查询。在视图中,我们使用 EJS 模板引擎来生成分页链接。
阅读全文