コンテンツにスキップ

JSONをPOSTする

JSONデータを使ってPOSTリクエストを送信します。外部サーバーとデータを共有するために使用します。

export default {
async fetch(request) {
/**
* 例としてsomeHostはJSONリクエストを受け取るように設定されています
* リクエストを送信したいホストでurlを置き換えてください
* @param {string} url リクエストを送信するURL
* @param {BodyInit} body リクエストに送信するJSONデータ
*/
const someHost = "https://examples.cloudflareworkers.com/demos";
const url = someHost + "/requests/json";
const body = {
results: ["送信するデフォルトデータ"],
errors: null,
msg: "これをfetchに送信しました",
};
/**
* gatherResponseはレスポンスボディを文字列として待機し、返します。
* async関数内でawait gatherResponse(..)を使用してレスポンスボディを取得します
* @param {Response} response
*/
async function gatherResponse(response) {
const { headers } = response;
const contentType = headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return JSON.stringify(await response.json());
} else if (contentType.includes("application/text")) {
return response.text();
} else if (contentType.includes("text/html")) {
return response.text();
} else {
return response.text();
}
}
const init = {
body: JSON.stringify(body),
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
};
const response = await fetch(url, init);
const results = await gatherResponse(response);
return new Response(results, init);
},
};