使用 Node.js Express 路由实现动态颜色网页

本示例展示如何使用 Node.js Express 的 router.get 方法创建一个简单的网页,页面标题和文本颜色会循环变化。

实现步骤

  1. 创建颜色数组:
const colors = ['red', 'yellow', 'green', 'blue'];
  1. 初始化颜色索引:
let currentColorIndex = 0;
  1. 定义路由处理函数:
router.get('/color.html', (req, res) => {
  const currentColor = colors[currentColorIndex];
  const html = `<html><head><title>${currentColor} color page</title></head><body><h1 style='color: ${currentColor}'>${currentColor.toUpperCase()}</h1></body></html>`;
  res.send(html);
  currentColorIndex = (currentColorIndex + 1) % colors.length;
});

代码解释

  • router.get('/color.html', ...): 定义一个处理 /color.html 路径的 GET 请求的路由。
  • currentColor = colors[currentColorIndex]: 获取当前颜色,并使用 currentColorIndex 从颜色数组中获取。
  • html = ...: 使用模板字符串创建 HTML 内容。标题和 h1 标签的文本颜色都设置为 currentColor
  • res.send(html): 将生成的 HTML 内容作为响应发送给客户端。
  • currentColorIndex = (currentColorIndex + 1) % colors.length;: 更新 currentColorIndex,确保在循环访问颜色数组时,索引能够重置为 0。

运行结果

每次访问 /color.html 页面时,页面标题和文本颜色都会循环变化,依次显示为红色、黄色、绿色、蓝色,并再次从红色开始。

总结

这个简单的示例演示了如何使用 Node.js Express 的 router.get 方法创建一个动态网页,并使用简单的逻辑来控制页面的外观。你可以根据需要扩展这个示例,添加更多功能,例如使用其他颜色、添加更多元素等等。


原文地址: https://www.cveoy.top/t/topic/mrfi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录