You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据请求百分比控制Node.js服务器的返回响应内容

实现方案

前置依赖

只需要用到Node.js原生的http模块即可,不需要额外安装第三方依赖。

具体操作步骤

  • 第一步:创建一个新的js文件,比如命名为server.js,写入以下代码:
const http = require('http');

const PORT = 3000;

const server = http.createServer((req, res) => {
  // 设置响应头避免中文乱码
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  // 生成0-99的随机整数
  const random = Math.floor(Math.random() * 100);
  // 20%概率返回hello,剩余返回hello world
  if (random < 20) {
    res.end('hello');
  } else {
    res.end('hello world');
  }
});

server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
  • 第二步:在终端执行命令启动服务器:
    node server.js
  • 第三步:验证效果,多次访问http://localhost:3000即可看到对应返回结果,请求量越大,返回占比越接近20%/80%的设定值。

精准占比调整方案

如果需要更严格的比例控制,不想受随机数偏差影响,可以用计数器替代随机逻辑,每10个请求固定返回2次hello、8次hello world,调整后代码如下:

const http = require('http');

const PORT = 3000;
// 全局计数器记录请求次数
let reqCount = 0;

const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  reqCount++;
  // 每10个请求为一个周期,前2个返回hello
  if (reqCount % 10 > 0 && reqCount % 10 <= 2) {
    res.end('hello');
  } else {
    res.end('hello world');
  }
});

server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

内容的提问来源于stack exchange,提问作者Shivam Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 07:36:02