Reputation: 567
I have a React Native app making POST requests to a Rails backend. Even though I inserted protect_from_forgery with: :null_session
in the ApplicationController
. All the POST requests I make are failing and I'm getting the error:
Can't verify CSRF token authenticity
This is one of the controllers in my Rails backend that I make the POST request to:
class AddressesController < ApplicationController
def show
address = Address.find(params[:id])
end
def create
address = Address.new(address_params)
if address.save
render json: {status: 'address created successfully'}, status: :create
else
render json: { errors: address.errors.full_messages }, status: :bad_request
end
end
def address_params
params.require(:address).permit(:streetname, :zipcode, :city, :country)
end
end
I've also tried to protect_from_forgery unless: -> { request.format.json? }
as I'm sending a JSON POST request, but still I'm getting the same error. Can anyone offer a different solution? Any help would be much appreciated! Thanks in Advance!
Question Update:
I followed what this guy did in this link. And I inserted the following instead:
class ApplicationController < ActionController::Base
skip_before_action :verify_authenticity_token
end
Now I'm not getting "Can't verify CSRF token authenticity" as an error, but I'm still getting an 500 (Internal Server Error) response from my server in the terminal. The values are not being saved for some reason. This is the error, I get:
Address Create (0.4ms) INSERT INTO "addresses" ("streetname", "zipcode", "city", "country", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["streetname", "Imenstrade 39"], ["zipcode", "1082AK"], ["city", "Amsterdam"], ["country", "The Netherlands"], ["created_at", "2018-08-29 12:23:22.261020"], ["updated_at", "2018-08-29 12:23:22.261020"]]
↳ app/controllers/addresses_controller.rb:10
(2.2ms) commit transaction
↳ app/controllers/addresses_controller.rb:10
Completed 500 Internal Server Error in 12ms (Views: 0.2ms | ActiveRecord: 3.2ms)
Upvotes: 1
Views: 1145
Reputation: 2668
You can ActionController::API
instead of ApplicationController
, and I see a syntax error you wrote status: :create
instead of status: :created
Upvotes: 1