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

如何让Node.js定时请求接口仅返回新增JSON数据?

嘿,我来帮你搞定这个定时获取新增帖子的问题!你的核心需求是每隔X分钟拉取一次接口,只输出自上次调用后新增的条目,之前尝试用ID数组对比没成功,其实我们可以简化思路——只需要记录上次获取到的最大ID,每次请求后过滤出ID大于这个值的帖子就行。

解决方案思路

  1. 记录上次最大ID:用一个变量保存上次拉取到的帖子里最大的ID,初始值设为0,这样第一次运行会获取全部帖子。
  2. 过滤新增内容:每次请求接口后,筛选出ID大于lastMaxId的帖子,这些就是新增的。
  3. 定时执行任务:用setInterval实现定时调用,注意时间单位是毫秒(比如5分钟就是5*60*1000)。
  4. 错误处理:添加请求失败的异常处理,避免程序崩溃。

修改后的代码(基于你用的request库)

注意:request库已经停止维护了,推荐后续换成axios或node-fetch,不过先基于你的现有代码修改:

var request = require("request");
var url = "https://jsonplaceholder.typicode.com/posts/";

// 保存上次获取到的最大ID,初始为0
let lastMaxId = 0;

// 封装请求和处理逻辑的函数
function fetchNewPosts() {
  request({ url: url, json: true }, function callback(error, response, body) {
    // 处理请求错误或非200状态码
    if (error || response.statusCode !== 200) {
      console.error("请求出错:", error || `状态码异常: ${response.statusCode}`);
      return;
    }

    // 过滤出ID大于lastMaxId的新增帖子
    const newPosts = body.filter(post => post.id > lastMaxId);

    if (newPosts.length === 0) {
      console.log("本次没有新增帖子");
      return;
    }

    // 输出新增帖子内容
    newPosts.forEach(post => {
      console.log(`ID: ${post.id}`);
      console.log(`标题: ${post.title}`);
      console.log(`内容: ${post.body}`);
      console.log("------------------------");
    });

    // 更新lastMaxId为当前所有帖子的最大ID
    const currentMaxId = Math.max(...body.map(post => post.id));
    lastMaxId = currentMaxId;
  });
}

// 第一次运行立即执行一次
fetchNewPosts();

// 设置定时任务,这里设为5分钟执行一次(可自行修改)
const intervalMinutes = 5;
setInterval(fetchNewPosts, intervalMinutes * 60 * 1000);

更现代的替代方案(用axios)

因为request已废弃,推荐用axios(需要先执行npm install axios安装),代码更简洁易读:

const axios = require("axios");
const url = "https://jsonplaceholder.typicode.com/posts/";

let lastMaxId = 0;

// 用async/await简化异步逻辑
async function fetchNewPosts() {
  try {
    const response = await axios.get(url);
    const posts = response.data;

    const newPosts = posts.filter(post => post.id > lastMaxId);

    if (newPosts.length === 0) {
      console.log("本次没有新增帖子");
      return;
    }

    newPosts.forEach(post => {
      console.log(`ID: ${post.id}`);
      console.log(`标题: ${post.title}`);
      console.log(`内容: ${post.body}`);
      console.log("------------------------");
    });

    lastMaxId = Math.max(...posts.map(post => post.id));
  } catch (error) {
    console.error("请求出错:", error.message);
  }
}

fetchNewPosts();
const intervalMinutes = 5;
setInterval(fetchNewPosts, intervalMinutes * 60 * 1000);

额外提示

  • 测试时,你可以手动修改lastMaxId的值(比如设为50),这样运行后会输出ID51-100的帖子,模拟新增效果(因为jsonplaceholder的帖子是固定的,不会真的新增)。
  • 如果需要持久化记录lastMaxId(比如重启服务后不丢失),可以把这个值写入本地文件(用fs模块)或者存入数据库(比如SQLite、MongoDB)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:13:42