Sending POST Requests With window.fetch In Rails

kinopyo avatar

kinopyo

TL;DR

Be sure to include the CSRF token into the headers, otherwise, you'll run into InvalidAuthenticityToken exception.

const csrfToken = document.querySelector("[name='csrf-token']").content;

fetch("/v1/articles", {
  method: "POST",
  headers: {
    "X-CSRF-Token": csrfToken,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ title: "awesome post" })
}).then(response => {
  if (!response.ok) { throw response; }
  return response.json();
}).then((data) => {
  console.log(data);
}).catch(error => {
  console.error("error", error);
});

In old-fashioned Rails apps, CSRF token is handled by rails-ujs transparently so there is no extra work for you.
However, if you're running Rails + React combo (or any other Single Page Application type apps) where you want to fire the raw requests from the frontend, you'll need to do what the code snippet above shows: grab the CSRF token from the markup and pass it in the headers.

credentials: "same-origin"

During my quick research, all examples I found on the internet have included credentials: "same-origin" in the request parameters, e.g.

fetch("/v1/articles", {
  // method, headers, body omitted
  credentials: "same-origin"
})

According to the MDN article , the default credentials value of fetch() has been changed from omit to same-origin:

Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.

Great, one less thing to configure! ๐Ÿ‘

Read More

kinopyo avatar
Written By

kinopyo

Indoor enthusiast, web developer, and former hardcore RTS gamer. #parenting
Published in Rails
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.