diff --git a/docs/latest/advanced/forms.md b/docs/latest/advanced/forms.md index e628880f..badab3e3 100644 --- a/docs/latest/advanced/forms.md +++ b/docs/latest/advanced/forms.md @@ -102,6 +102,12 @@ export default define.page(function Upload(props) { }); ``` +## Other HTTP methods + +Browsers can only submit forms as `GET` or `POST`. To submit a form as `DELETE`, +`PATCH` or `PUT` and update part of the page with the response, use +[Partials](/docs/advanced/partials#using-other-http-methods). + ## A note of caution These examples are simplified to demonstrate how Deno and Fresh handle HTTP diff --git a/docs/latest/advanced/partials.md b/docs/latest/advanced/partials.md index 5626dc1c..1eee088c 100644 --- a/docs/latest/advanced/partials.md +++ b/docs/latest/advanced/partials.md @@ -145,6 +145,80 @@ two links and _only_ load the content rendered by our optimized partial route. > Currently, `f-partial` is scoped to ``, ` + + + + nothing submitted yet + + ); +}); +``` + +A form that uses another method is always submitted as a partial request. It +doesn't need an `action` or `f-partial` attribute. Without them, the request +goes to the current page. You can write the method in any case: Fresh converts +it to uppercase, so `formmethod="patch"` reaches your `PATCH` handler. + +The `POST` button above only submits as a partial because the form has an +`action` attribute. Without it, `POST` would cause a full page load, while the +`DELETE` and `PATCH` buttons would still work as partials. + +Keep the following in mind when using other methods: + +- **Redirects:** To redirect after a `DELETE`, `PATCH` or `PUT`, respond with + status `303 See Other`. With a `301` or `302`, `fetch()` sends the request to + the new URL again with the same method. +- **Without JavaScript:** If JavaScript isn't loaded, the browser doesn't + recognize the method and submits the form as a `GET` request instead, with the + fields in the URL. If a form has to work without JavaScript, use `POST`. +- **CSRF protection:** The [CSRF middleware](/docs/plugins/csrf) treats these + methods like `POST`, so they get the same checks. + ## Sending multiple Partials at the same time A neat aspect of partials in Fresh is that a response can return as many diff --git a/packages/fresh/src/runtime/client/partials.ts b/packages/fresh/src/runtime/client/partials.ts index 008e23a9..b3daabd0 100644 --- a/packages/fresh/src/runtime/client/partials.ts +++ b/packages/fresh/src/runtime/client/partials.ts @@ -262,14 +262,17 @@ document.addEventListener("submit", async (e) => { return; } - const lowerMethod = - e.submitter?.getAttribute("formmethod")?.toLowerCase() ?? - el.method.toLowerCase(); - if (lowerMethod !== "get" && lowerMethod !== "post") { + const method = e.submitter?.getAttribute("formmethod")?.toLowerCase() || + el.getAttribute("method")?.toLowerCase() || "get"; + + if (method === "dialog") { return; } - const hasExplicitPartial = e.submitter?.hasAttribute(PARTIAL_ATTR) || + const isCustomMethod = method !== "get" && method !== "post"; + + const hasExplicitPartial = isCustomMethod || + e.submitter?.hasAttribute(PARTIAL_ATTR) || e.submitter?.hasAttribute("formaction") || el.hasAttribute(PARTIAL_ATTR) || el.hasAttribute("action"); @@ -300,13 +303,16 @@ document.addEventListener("submit", async (e) => { let init: RequestInit | undefined; // GET method appends form data via url search params - if (lowerMethod === "get") { + if (method === "get") { // TODO: Looks like constructor type for URLSearchParam is wrong // deno-lint-ignore no-explicit-any const qs = new URLSearchParams(new FormData(el, e.submitter) as any); qs.forEach((value, key) => partialUrl.searchParams.append(key, value)); } else { - init = { body: new FormData(el, e.submitter), method: lowerMethod }; + init = { + body: new FormData(el, e.submitter), + method: method?.toUpperCase(), + }; } try { diff --git a/packages/fresh/tests/partials_test.tsx b/packages/fresh/tests/partials_test.tsx index c8a08755..53271ee7 100644 --- a/packages/fresh/tests/partials_test.tsx +++ b/packages/fresh/tests/partials_test.tsx @@ -1,4 +1,4 @@ -import { App, staticFiles } from "sweet"; +import { App, type Context, staticFiles } from "sweet"; import { Partial } from "sweet/runtime"; import { ALL_ISLAND_DIR, @@ -1955,6 +1955,201 @@ Deno.test({ }, }); +async function renderMethodPartial(ctx: Context) { + const data = await ctx.req.formData(); + const name = data.get("name"); + return ctx.render( + + +

done

+
+
, + ); +} + +Deno.test({ + name: "partials - submit form with formmethod DELETE, PATCH and PUT", + fn: async () => { + const app = testApp() + .delete("/", renderMethodPartial) + .patch("/", renderMethodPartial) + .put("/", renderMethodPartial) + .get("/", (ctx) => { + return ctx.render( + +
+
+ + + + + + + +

init

+
+
+
, + ); + }); + + await withBrowserApp(app, async (page, address) => { + await page.goto(address, { waitUntil: "load" }); + await page.locator(".ready").wait(); + + await page.locator(".increment").click(); + await waitForText(page, ".output", "1"); + + await page.locator(".delete").click(); + await page.locator(".done-DELETE-foo").wait(); + + await page.locator(".patch").click(); + await page.locator(".done-PATCH-foo").wait(); + + await page.locator(".put").click(); + await page.locator(".done-PUT-foo").wait(); + + // Island state survives, so no full page reload happened + await waitForText(page, ".output", "1"); + }); + }, +}); + +Deno.test({ + name: "partials - submit form with custom method on form element", + fn: async () => { + const app = testApp() + .patch("/", renderMethodPartial) + .get("/", (ctx) => { + return ctx.render( + +
+
+ + + +

init

+
+ + +
+
, + ); + }); + + await withBrowserApp(app, async (page, address) => { + await page.goto(address, { waitUntil: "load" }); + await page.locator(".ready").wait(); + + await page.locator(".increment").click(); + await waitForText(page, ".output", "1"); + + await page.locator(".update").click(); + await page.locator(".done-PATCH-foo").wait(); + await waitForText(page, ".output", "1"); + }); + }, +}); + +Deno.test({ + name: "partials - form without method inside f-client-nav not intercepted", + fn: async () => { + const app = testApp() + .get("/", (ctx) => { + if (ctx.url.searchParams.has("name")) { + return ctx.render( + + + , + ); + } + + return ctx.render( + +
+
+ + +

init

+
+ +
+
+
, + ); + }); + + await withBrowserApp(app, async (page, address) => { + await page.goto(address, { waitUntil: "load" }); + await page.locator(".init").wait(); + + await Promise.all([ + page.waitForNavigation(), + page.locator(".update").click(), + ]); + await page.locator(".submitted").wait(); + + const search = await page.evaluate(() => window.location.search); + expect(search).toEqual("?name=foo"); + }); + }, +}); + +Deno.test({ + name: "partials - submit form DELETE with 303 redirect", + fn: async () => { + const app = testApp() + .get("/done", (ctx) => { + return ctx.render( + + +

deleted

+
+
, + ); + }) + .delete("/", () => { + return new Response(null, { + status: 303, + headers: { Location: "/done" }, + }); + }) + .get("/", (ctx) => { + return ctx.render( + +
+
+ +

init

+
+ +
+
+
, + ); + }); + + await withBrowserApp(app, async (page, address) => { + await page.goto(address, { waitUntil: "load" }); + await page.locator(".init").wait(); + + await page.locator(".update").click(); + await page.locator(".done").wait(); + + const pathname = await page.evaluate(() => window.location.pathname); + expect(pathname).toEqual("/done"); + }); + }, +}); + Deno.test({ name: "partials - submit form via external submitter", fn: async () => {