Api Integration
指导前端与后端API集成的类型、错误、鉴权及实时通信设计规范。
下载 255
基于 Node.js 内置模块的 HTTP 客户端,支持自动重试与错误处理。
openclaw skills install @stephen-standridge/simplehttpskill命令、参数、文件名以原文为准
使用 Node.js 内置模块发起 HTTP 请求。支持所有标准方法、任意请求头、自动重试(指数退避),且从不抛出异常 —— 始终以可检查的响应对象进行解析。
GET。3。30000。src/http-client.js 导入客户端:const { HttpClient } = require("./src/http-client");const client = new HttpClient({
defaultHeaders: { Authorization: "Bearer <token>" },
maxRetries: 3,
});request() 发起请求:// GET
const resp = await client.get("https://api.example.com/items");
// POST 附带 JSON 请求体
const resp = await client.post("https://api.example.com/items", {
body: { name: "widget" },
});
// PUT 附带自定义请求头
const resp = await client.put("https://api.example.com/items/1", {
headers: { "X-Request-Id": "abc123" },
body: { name: "updated" },
});
// DELETE
const resp = await client.delete("https://api.example.com/items/1");
// 通用形式 —— 支持任意方法
const resp = await client.request("PATCH", "https://api.example.com/items/1", {
body: { qty: 5 },
});if (resp.ok) {
console.log(resp.body); // 解析后的 JSON 或原始字符串
console.log(resp.status); // 例如 200
console.log(resp.headers); // 响应头对象
} else {
console.log(resp.error); // 可读的错误信息(若为 HTTP 错误则为 null)
console.log(resp.status); // HTTP 状态码;网络错误时为 null
}每次调用都会返回一个包含以下字段的对象:
| 字段 | 类型 | 描述 |
|---|---|---|
ok | boolean | 状态码为 2xx 时为 true |
status | `number \ | null` |
headers | object | 响应头 |
body | any | 若 Content-Type 为 JSON 则解析为对象,否则为字符串 |
error | `string \ | null` |
resp.ok 和 resp.error。所有选项可在客户端级别(构造函数中)设置,并在单次请求中覆盖:
| 选项 | 默认值 | 描述 |
|---|---|---|
defaultHeaders | {} | 应用于每次请求的请求头 |
maxRetries | 3 | 最大重试次数 |
timeout | 30000 | Socket 超时时间(毫秒) |
backoffBase | 500 | 指数退避的基础延迟(毫秒) |
backoffMax | 30000 | 退避延迟上限(毫秒) |
无外部依赖 —— 仅使用 Node.js 内置模块(http、https、url)。
已收录 1 个 Skill