使用 Node.js 限制网页访问次数

本文将介绍如何使用 Node.js 实现网页访问次数限制的功能,例如限制用户只能访问网页 10 次。

代码示例

const http = require('http');

let count = 0;

const server = http.createServer((req, res) => {
  count++;
  if (count > 10) {
    res.writeHead(403, { 'Content-Type': 'text/plain' });
    res.end('Sorry, you have exceeded the maximum number of requests.');
  } else {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World!');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

代码解释

  1. 使用 http 模块创建 HTTP 服务器。
  2. 使用 count 变量记录网页的访问次数。
  3. 每次接收到请求时,将 count 变量加 1。
  4. 如果 count 超过 10,则返回 HTTP 403 Forbidden 状态码和错误消息,表示访问次数已超过限制。
  5. 如果 count 未超过 10,则返回 HTTP 200 OK 状态码和欢迎消息。

运行代码

  1. 将代码保存为 app.js 文件。
  2. 在终端中切换到代码所在的目录。
  3. 运行以下命令启动服务器:
node app.js
  1. 在浏览器中打开 http://localhost:3000/,并连续访问该页面多次以测试代码功能。
  2. 在第 11 次访问时,您将看到错误消息。

总结

本文提供了一个简单的示例,演示了如何使用 Node.js 限制网页访问次数。您可以根据自己的需求调整代码,例如使用数据库存储访问次数,实现更复杂的限制策略。

Node.js 实现网页使用次数限制 - 限制访问次数

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

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