使用 Node.js Express 实现循环颜色标题网页
使用 Node.js Express 实现循环颜色标题网页
本教程将教你如何使用 Node.js 的 Express 框架创建一个简单的网页,其标题颜色会随着每次访问循环变化,从红色、黄色、绿色到蓝色。
实现步骤
-
创建路由:
使用 Express 的
router.get()方法创建一个处理/color.html路径的 GET 请求的路由。 -
定义颜色数组:
创建一个包含四种颜色名称的数组:
['red', 'yellow', 'green', 'blue']。 -
使用索引控制颜色:
定义一个变量
currentIndex来跟踪当前颜色在数组中的索引,初始值为 0。 -
生成 HTML 内容:
在路由处理函数中,获取
colors数组中当前索引的颜色,并将其用作标题和页面背景颜色。使用模板字符串生成 HTML 代码。 -
发送响应:
使用
res.send()发送生成的 HTML 内容作为响应。 -
更新索引:
在发送响应后,更新
currentIndex,使其指向下一个颜色索引。如果到达数组的末尾,将currentIndex重置为 0,从而实现循环。
代码示例
const colors = ['red', 'yellow', 'green', 'blue'];
let currentIndex = 0;
router.get('/color.html', (req, res) => {
const color = colors[currentIndex];
const html = `
<html>
<head>
<title>'${color}' color</title>
</head>
<body>
<h1 style='color: '${color}'>'${color}'</h1>
</body>
</html>
`;
res.send(html);
currentIndex = (currentIndex + 1) % colors.length;
});
解释
router.get('/color.html', ...):处理针对/color.html路径的 GET 请求。const color = colors[currentIndex];:获取当前颜色。const html = ...:使用模板字符串生成 HTML 代码。res.send(html);:发送生成的 HTML 内容作为响应。currentIndex = (currentIndex + 1) % colors.length;:更新索引,使其指向下一个颜色索引,并使用模运算符 (%) 实现循环。
运行结果
每次访问 /color.html 页面时,页面标题颜色将依次循环变化:红色、黄色、绿色、蓝色,然后从红色开始循环。
总结
本教程演示了使用 Node.js Express 框架创建动态网页的基本步骤,通过使用路由、数组和索引控制,实现了一个简单的循环颜色标题网页。你可以根据需要修改颜色数组、添加其他内容或功能,扩展这个示例。
原文地址: https://www.cveoy.top/t/topic/mrfm 著作权归作者所有。请勿转载和采集!