jjzjj

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

coder 2023-12-11 原文

我将使用 Ruby on Rails 创建 restful API。我想创建、删除、显示和更新数据。所有这些都必须是 JSON 才能在 Android 设备中获取。我还使用 Postman 检查我的 API。 这就是我所做的:

我的 Controller :

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

这是我的路线文件:

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

并且还在我的 Gemfile 中添加了以下代码:

gem "devise"
gem 'active_model_serializers'

我不知道为什么当我想通过 postman 创建时出现以下错误:

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

最佳答案

您需要在 application_controller.rb 中进行以下更改

改变

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

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

编辑

更好的方法是跳过特定 Controller 的身份验证

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

  respond_to :json
  # ...
end

关于android - ActionController InvalidAuthenticityToken in Api::V1::UsersController#create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41619177/

有关android - ActionController InvalidAuthenticityToken in Api::V1::UsersController#create的更多相关文章

随机推荐