Node.js Express 路由示例:循环显示颜色标题

本示例展示如何使用 Node.js Express 创建一个简单的网页,通过 GET 路由显示不同颜色标题,每次访问页面时颜色循环变化。

代码实现

const express = require('express');
const app = express();

let colors = ['red', 'yellow', 'green', 'blue'];
let currentColorIndex = 0;

app.get('/color.html', (req, res) => {
  let currentColor = colors[currentColorIndex];
  let html = `<html><head><title>${currentColor} color</title></head><body><h1 style='color:${currentColor}'>${currentColor}</h1></body></html>`;
  res.send(html);

  currentColorIndex++;
  if (currentColorIndex >= colors.length) {
    currentColorIndex = 0;
  }
});

app.listen(3000, () => console.log('Server started on port 3000')); 

代码解释

  1. 定义颜色数组: colors 数组包含四种颜色:红色、黄色、绿色和蓝色。
  2. 定义当前颜色索引: currentColorIndex 变量用于跟踪当前显示的颜色。初始值为 0,表示第一个颜色。
  3. 处理 GET 请求: 当接收到 /color.html 的 GET 请求时,执行以下操作:
    • 获取当前颜色:根据 currentColorIndexcolors 数组中获取当前颜色。
    • 生成 HTML 代码:使用当前颜色创建包含标题的 HTML 代码。
    • 发送响应:将生成的 HTML 代码作为响应发送给客户端。
    • 递增索引:currentColorIndex 加 1,用于下次访问时显示下一个颜色。
    • 重置索引:如果 currentColorIndex 超过颜色数组的长度,则将其重置为 0,开始新一轮循环。

运行示例

  1. 确保已经安装 Node.js 和 Express。
  2. 将代码保存为 app.js 文件。
  3. 在终端中运行 node app.js 启动服务器。
  4. 在浏览器中访问 http://localhost:3000/color.html,您将看到一个颜色标题,每次刷新页面时颜色都会循环变化。

功能说明

  • 该示例展示了使用 Express 处理 GET 请求的简单方法。
  • 通过定义一个数组和索引,可以实现循环显示不同内容或样式的效果。
  • 该示例可以作为基础,用于创建更多动态网页内容,例如轮播图、计数器等。
Node.js Express 路由示例:循环显示颜色标题

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

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