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

如何使用node-fetch高效发送3次POST请求 解决仅第一个请求生效问题

问题修复与最优实现方案

现有代码的核心问题

  • 三个请求配置的body全部硬编码为obj1,即使发起多次请求也只会提交第一个用户的数据
  • createUser函数仅设计接收2个参数(url + 单组请求配置),传入多组配置也不会被处理,自然只会发起1次请求

最高效实现方案

因为API不支持批量提交,我们可以用Promise.all并行发起3次独立请求,同时完全消除重复代码,不需要手动声明3个请求配置对象:

import fetch from 'node-fetch';
import xlsx from 'xlsx';
const baseUrl = "";
const apiToken = "";
// 注意原代码漏了accountId的声明,此处按需补充即可
const accountId = "";

const wb = xlsx.readFile('users.xlsx');
const ws = wb.Sheets['users'];
const data = xlsx.utils.sheet_to_json(ws);

// 抽离公共请求配置,避免重复编码
const BASE_OPTIONS = {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiToken}`,
    "gtmhub-accountid": accountId,
    "Content-type": "application/json; charset=UTF-8",
    Accept: "application/json, text/plain, */*",
  }
};

// 单用户创建逻辑复用
const createUser = async (userObj) => {
  const options = {
    ...BASE_OPTIONS,
    body: JSON.stringify(userObj)
  };
  try {
    const response = await fetch(`${baseUrl}/users`, options);
    const resData = await response.text();
    console.log(`用户${userObj.name || '未知'}创建成功:`, resData);
    return resData;
  } catch (error) {
    console.error(`用户${userObj.name || '未知'}创建失败:`, error.message);
    throw error;
  }
};

// 并行发起三次请求,效率最高,三个请求同时发送
Promise.all(data.slice(0,3).map(user => createUser(user)))
  .then(results => console.log('所有用户创建完成', results))
  .catch(err => console.error('有用户创建失败', err));

特殊场景适配

如果API有调用频率限制,不支持并行请求,可以改成串行执行:

// 串行逐个发起请求
(async () => {
  for (const user of data.slice(0,3)) {
    await createUser(user);
  }
  console.log('所有用户创建完成');
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:48:03