4

I'm trying to build a JSON API for my Rails application, and have written the following method:

  def create
    organization = Organization.find(params[:organization][:node_id])
    node = organization.nodes.build(nodes_params.except[:id])
    if node.save
      render json: node, status: :ok
    else
      render json: node, status: :bad_request
    end
  end

Trying the method in Postman returns the error: "Can't verify CSRF token authenticity". Based on this post I added the code below to the base controller. Unfortunately this made no difference. Does anyone understand the cause of the error?

protect_from_forgery
skip_before_action :verify_authenticity_token, if: :json_request?
private
  def json_request?
    request.format.json?
  end
5
  • Possible duplicate of stackoverflow.com/questions/9362910/… Commented Jan 18, 2016 at 9:48
  • Which rails environment do you use to test your controller's method? Commented Jan 18, 2016 at 10:01
  • I'm using the development environment (using Cloud9 IDE). Right now trying to figure out the post @MaxWilliams suggested. Commented Jan 18, 2016 at 10:10
  • If you want just to test the organization creation with json request try starting rails in test environment. Commented Jan 18, 2016 at 10:17
  • Thanks, I got it to work with protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == 'application/json' } Commented Jan 18, 2016 at 10:32

1 Answer 1

5

As per comment on application_controller.rb you need to put this line protect_from_forgery with: :null_session.

It will better if you make one more root controller for only all API's controller which is inherited from ApplicationController. i.e

class Api::ApiController < ApplicationController
  #TODO
  protect_from_forgery with: :null_session
end

Other API's controllers

class Api::V1::AddressesController < Api::ApiController
  #TODO
end

This controller class can help you to make changes only for API's root rather than whole application. You can also use this controller to make D.R.Y actions between various versions of API's.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.