javascript fetch api 本身不具备自动负载均衡能力,需通过手动维护健康实例列表、轮询或随机选择目标节点并发起独立请求来实现。具体做法是预定义一组后端服务地址,在每次调用时按策略选取一个 url,使用 fetch() 向该地址发送请求,并根据响应状态码判断是否重试或切换节点。

如何基于健康检查动态筛选可用接口地址
通过定期探测各节点存活状态,仅将返回成功的地址加入候选池,从而避免向故障节点发送请求。实现方式是设置定时器执行 HEAD 或轻量级 GET 请求,记录成功响应的节点索引,后续请求仅从有效列表中随机抽取。

const endpoints = [
'https://api-node-1.example.com/data',
'https://api-node-2.example.com/data',
'https://api-node-3.example.com/data'
];
let healthyEndpoints = [...endpoints];
async function checkHealth() {
const results = await Promise.allSettled(
endpoints.map(url => fetch(url, { method: 'HEAD' }).then(r => r.ok ? url : null))
);
healthyEndpoints = results
.filter(r => r.status === 'fulfilled' && r.value)
.map(r => r.value);
}
setInterval(checkHealth, 5000);
如何在请求失败时自动切换到备用节点
当主选节点返回非 2xx 状态码或网络异常时,立即从剩余健康节点中重新选择一个地址进行重试,确保单次业务请求不因单点故障而中断。核心逻辑是在 catch 块中更新候选集并递归调用请求函数,直到所有节点耗尽或请求成功。

async function loadBalancedFetch(url, options = {}) {
if (healthyEndpoints.length === 0) {
throw new Error('No healthy endpoints available');
}
const targetIndex = Math.floor(Math.random() * healthyEndpoints.length);
const targetUrl = healthyEndpoints[targetIndex];
try {
const response = await fetch(targetUrl, options);
if (!response.ok) {
// Remove failed endpoint from healthy list
healthyEndpoints.splice(targetIndex, 1);
return loadBalancedFetch(url, options); // Retry with remaining
}
return response;
} catch (error) {
// Network error, remove endpoint and retry
healthyEndpoints.splice(targetIndex, 1);
return loadBalancedFetch(url, options);
}
}
当所有健康节点均返回 503 错误时程序如何处理
若所有候选节点均返回 503 Service Unavailable,说明集群整体不可用,此时不再重试,而是直接抛出包含当前健康状态的错误对象,由上层业务逻辑决定降级策略或展示用户提示。代码中通过检查 healthyEndpoints 是否为空或全部失效来触发最终异常抛出,避免无限循环重试。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











