Skip to main content

Fetch JSON

还没翻译译自英文(developers.cloudflare.com)本页 8 段都还没译

If you want to get started quickly, click on the button below.

Deploy to Cloudflare

This creates a repository in your GitHub account and deploys the application to Cloudflare Workers.

JavaScriptTypeScriptPythonHono

export default {
	async fetch(request, env, ctx) {
		const url = "https://jsonplaceholder.typicode.com/todos/1";

		// gatherResponse returns both content-type & response body as a string
		async function gatherResponse(response) {
			const { headers } = response;
			const contentType = headers.get("content-type") || "";
			if (contentType.includes("application/json")) {
				return { contentType, result: JSON.stringify(await response.json()) };
			}
			return { contentType, result: await response.text() };
		}

		const response = await fetch(url);
		const { contentType, result } = await gatherResponse(response);

		const options = { headers: { "content-type": contentType } };
		return new Response(result, options);
	},
};