Once Rails is probably configured in our Rails application, we are not out of the jungle yet. We will also need to properly configure our applications such that our fetch requests communicate effectively with Rails. Let's briefly touch on these:
Rails has built in securities and config that make it very selective about the requests that are allowed to come in. We'll need to edit our controller configuration to allow fetch requests and their json formats so that we can respond accordingly.
First, if you have an ApiController.rb
that all other API controllers inherit from, we will want to add a line that skips the verification
of the authenticity token that Rails normally assumes you will pass it.
class ApiController < ApplicationController
skip_before_action :verify_authenticity_token
end
If you chooose not to have an Api controller, than you will need to add this line to the top of each of your API controller files.
If you are still running into an error where there is a missing CSRF
token, you may also need to add protect_from_forgery unless: -> { request.format.json? }
but this should normally not be needed.
We will also want to add some additional options to our fetch requests so that they are handled by Rails effectively.
Let's say we are reviewing fruits. We want to make a request to POST a new fruit, so that we can review this fruit in the future.
With POST requests in particular, its important we have the right options passed along.Make sure that you have both the credentials
option and headers
options below.
fetch(`/api/v1/fruits`, {
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify(formPayload),
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }
})
...
This way, our Rails application knows to trust this fetch request, and know that its from our frontend React application.