API: HTTP 请求
用于向外部服务和API发起HTTP请求的函数。
C++ 注册:regWeb(js)。
实现:jsWeb.h + NetCurl.h(libcurl的封装)。
http_get
http_get(url: string) → object
执行 HTTP GET 请求。
参数:
| 参数 | 类型 | 描述 |
|---|---|---|
url |
string | 包含协议(https://...)的完整URL |
返回值:
| 字段 | 类型 | 描述 |
|---|---|---|
status |
number | HTTP 响应码(200、404、500 等) |
body |
string | 响应体 |
error |
string | curl 错误信息或 "" |
示例:
let r = http_get("https://api.example.com/health");
if (r.error) {
console.log("请求错误:", r.error);
} else if (r.status !== 200) {
console.log("HTTP 错误:", r.status);
} else {
let data = JSON.parse(r.body);
console.log("响应:", JSON.stringify(data));
}
http_post
http_post(url: string, body: string, headers?: string[]) → object
执行 HTTP POST 请求。
参数:
| 参数 | 类型 | 描述 |
|---|---|---|
url |
string | 完整URL |
body |
string | 请求体(JSON、表单数据等) |
headers |
string[] | (可选) HTTP 头部数组 |
头部格式:
["Content-Type: application/json", "Authorization: Bearer TOKEN"]
返回值:
| 字段 | 类型 | 描述 |
|---|---|---|
status |
number | HTTP 响应码 |
body |
string | 响应体 |
error |
string | 错误信息或 "" |
示例:
// 发送 JSON
let payload = JSON.stringify({ event: "alert", level: "critical" });
let r = http_post(
"https://api.example.com/events",
payload,
["Content-Type: application/json"]
);
console.log(r.status, r.body);
// 带授权
let r2 = http_post(
"https://api.example.com/data",
JSON.stringify({ value: 42 }),
[
"Content-Type: application/json",
"Authorization: Bearer my_token_here"
]
);
// 不带头部(例如表单数据)
let r3 = http_post(
"https://example.com/form",
"name=John&age=30"
);
使用 Webhook
Discord
let url = "https://discord.com/api/webhooks/ID/TOKEN";
let r = http_post(url, JSON.stringify({
content: "警报!服务已宕机。"
}), ["Content-Type: application/json"]);
console.log(r.status); // 204 = 成功
Slack
let url = "https://hooks.slack.com/services/T.../B.../...";
let r = http_post(url, JSON.stringify({
text: "警报!服务已宕机。"
}), ["Content-Type: application/json"]);
console.log(r.status); // 200 = 成功
Telegram
let token = "BOT_TOKEN";
let chatId = "CHAT_ID";
let text = encodeURIComponent("警报!服务已宕机。");
let r = http_get(
"https://api.telegram.org/bot" + token +
"/sendMessage?chat_id=" + chatId + "&text=" + text
);
let resp = JSON.parse(r.body);
console.log(resp.ok); // true = 成功
错误处理
function safePost(url, payload, headers) {
let r = http_post(url, payload, headers);
// 网络错误 (curl)
if (r.error) {
console.log("[错误] 网络错误:", r.error);
return false;
}
// HTTP 错误
if (r.status < 200 || r.status >= 300) {
console.log("[错误] HTTP", r.status, ":", r.body);
return false;
}
return true;
}
HTTP 响应码
| 状态码 | 含义 |
|---|---|
| 200 | 成功 |
| 201 | 已创建 |
| 204 | 无内容(Discord webhook 成功) |
| 400 | 请求错误 |
| 401 | 未授权 |
| 403 | 禁止访问 |
| 404 | 未找到 |
| 429 | 请求过多(频率限制) |
| 500 | 服务器内部错误 |