API: HTTPリクエスト
外部サービスやAPIへのHTTPリクエストを行うための関数です。
C++登録: regWeb(js)。
実装: jsWeb.h + NetCurl.h (libcurlのラッパー)。
http_get
http_get(url: string) → object
HTTP GETリクエストを実行します。
パラメータ:
| パラメータ | 型 | 説明 |
|---|---|---|
url |
string | プロトコルを含む完全なURL (https://...) |
結果:
| フィールド | 型 | 説明 |
|---|---|---|
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("[ERROR] ネットワークエラー:", r.error);
return false;
}
// HTTPエラー
if (r.status < 200 || r.status >= 300) {
console.log("[ERROR] HTTP", r.status, ":", r.body);
return false;
}
return true;
}
HTTPレスポンスコード
| コード | 意味 |
|---|---|
| 200 | OK |
| 201 | Created |
| 204 | No Content (Discord webhook成功) |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 429 | Too Many Requests (レート制限) |
| 500 | Internal Server Error |