Jese Leos

When a HTTP Post Becomes a Patch

I was implementing the previews in PhrontPage.

Part of this involves grabbing the current form and sending the data via HTTPost (using requestjs-rails) to the server and then letting turbo_stream do its thing and update the screen.

const form = new FormData(formElement)
const response = await post(this.urlValue, {
   body: form,
   responseKind: "turbo-stream"
})

Full source in preview_controller.js

This was wired up to a controller like this:

post "/previews", to: "previews#show"

When working with new Posts or Pages, everything worked as expected.

However, once I tried to preview an existing Post or Page, I started getting 404 errors. Thankfully, it did not take me long to spot the error.

I believe it was Rails 4 when the switch was made to use the Patch verb for updates. Browsers do not typically support Patch. To get around this, Rails (and other frameworks) add a hidden field called _method.

patch.png

The browser declares a post request on the form. However, when Rails spots the '_method` parameter, it knows to look for the matching route. In my case, this did not exist at the time.

There are some simple fixes for this:

  1. Remove the _method from my FormData
  2. Supply a different route to handle existing Posts and Pages
  3. Update the route to work for both Post and Patch

I went with option #3. For the preview feature, it does not matter if the content already exists. I need to take what you have on the form and send it to the server.

The updated route looks like this:

match "/previews", to: "previews#show", via: [:patch, :post]