Skip to main content

Read POST

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

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.

JavaScriptTypeScriptPythonRustHono

export default {
	async fetch(request) {
		/**
		 * rawHtmlResponse returns HTML inputted directly
		 * into the worker script
		 * @param {string} html
		 */
		function rawHtmlResponse(html) {
			return new Response(html, {
				headers: {
					"content-type": "text/html;charset=UTF-8",
				},
			});
		}

		/**
		 * readRequestBody reads in the incoming request body
		 * Use await readRequestBody(..) in an async function to get the string
		 * @param {Request} request the incoming request to read from
		 */
		async function readRequestBody(request) {
			const contentType = request.headers.get("content-type");
			if (contentType.includes("application/json")) {
				return JSON.stringify(await request.json());
			} else if (contentType.includes("application/text")) {
				return request.text();
			} else if (contentType.includes("text/html")) {
				return request.text();
			} else if (contentType.includes("form")) {
				const formData = await request.formData();
				const body = {};
				for (const entry of formData.entries()) {
					body[entry[0]] = entry[1];
				}
				return JSON.stringify(body);
			} else {
				// Perhaps some other type of data was submitted in the form
				// like an image, or some other binary data.
				return "a file";
			}
		}

		const { url } = request;
		if (url.includes("form")) {
			return rawHtmlResponse(someForm);
		}
		if (request.method === "POST") {
			const reqBody = await readRequestBody(request);
			const retBody = `The request body sent in was ${reqBody}`;
			return new Response(retBody);
		} else if (request.method === "GET") {
			return new Response("The request was a GET");
		}
	},
};

Prevent potential errors when accessing request.body

The body of a Request can only be accessed once. If you previously used request.formData() in the same request, you may encounter a TypeError when attempting to access request.body.

To avoid errors, create a clone of the Request object with request.clone() for each subsequent attempt to access a Request's body. Keep in mind that Workers have a memory limit of 128 MB per Worker and loading particularly large files into a Worker's memory multiple times may reach this limit. To ensure memory usage does not reach this limit, consider using Streams.