2017-01-12 9 views
5

Zamierzam stworzyć restful API używając Ruby on Rails. Chcę tworzyć, usuwać, pokazywać i aktualizować dane. Wszystkie powinny być JSON, aby uzyskać je na urządzeniach z Androidem. Używam też Postmana do sprawdzania moich interfejsów API. To co zrobiłem:ActionController InvalidAuthenticityToken w Api :: V1 :: UsersController # create

My Kontroler:

class Api::V1::UsersController < ApplicationController 
    respond_to :json 

    def show 
     respond_with User.find(params[:id]) 
    end 

    def create 
     user=User.new(user_params) 
     if user.save 
      render json: user, status: 201 
     else 
      render json: {errors: user.errors}, status: 422 
     end 
    end 

    def update 
     user=User.find(params[:id]) 
     if user.update(user_params) 
      render json: user, status:200 
     else 
     render json: {erros: user.errors},status: 422 
     end 

    end 

    def destroy 
     user=User.find(params[:id]) 
     user.destroy 
     head 204 
    end 

    private 
    def user_params 
     params.require(:user).permit(:email,:password,:password_confirmation) 
    end 
end 

i to jest mój plik trasa:

Rails.application.routes.draw do 
    devise_for :users 
    namespace :api, defaults:{ format: :json } do 
    namespace :v1 do 
    resources :users, :only=>[:show,:create,:update,:destroy] 
    end 
    end 
end 

a także dodać następujący kod do mojego Gemfile:

gem "devise" 
gem 'active_model_serializers' 

Nie wiem, dlaczego, gdy chcę utworzyć za pośrednictwem listonosza, pojawia się następujący błąd:

ActionController InvalidAuthenticityToken in Api::V1::UsersController#create 

Odpowiedz

4

Trzeba wprowadzić następujące zmiany w application_controller.rb

Zmień

class ApplicationController < ActionController::Base 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 
end 

do

class ApplicationController < ActionController::Base 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :null_session 
end 

EDIT

Lepszym sposobem jest pominięcie autoryzacji określonego kontrolera.

class Api::V1::UsersController < ApplicationController 
    skip_before_action :verify_authenticity_token 

    respond_to :json 
    # ... 
end 
+0

Autor pytania nie podał jeszcze błędu. Ciekawi mnie, jak udało ci się dowiedzieć, jak rozwiązać problem. –

+0

Błąd jest w tytule pytania –

+0

Całkowicie to przeoczyłem. Dzięki. –

Powiązane problemy