API / JSON: unable to authenticate CSRF token

I am trying to create a JSON API for my Rails application and wrote 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

An attempt by a method in Postman returns an error: "Unable to verify the authenticity of the CSRF token." Based on this post , I added the code below to the base controller. Unfortunately, that didn't matter. 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
+4
source share
1 answer

According to the comment application_controller.rbyou need to put this line protect_from_forgery with: :null_session.

, API-, ApplicationController. iee

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

API

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

API root, . D.R.Y API.

+4

Source: https://habr.com/ru/post/1624759/


All Articles