我将使用Rails创建restful。我想要创建,删除,显示和更新数据。所有这些都必须是JSON才能在Android设备中实现。我还使用邮递员检查我的API。这就是我所做的:
我的财务主任:
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'
我不知道为什么当我想通过邮递员创建时,我会出现以下错误:
ActionController InvalidAuthenticityToken in Api::V1::UsersController#create
发布于 2017-01-12 17:23:55
您需要在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
编辑
更好的方法是跳过特定控制器的身份验证。
class Api::V1::UsersController < ApplicationController
skip_before_action :verify_authenticity_token
respond_to :json
# ...
end
发布于 2019-04-16 15:50:52
在application_controller.rb中
用于网络控制器
protect_from_forgery with: :exception
对于API控制器
protect_from_forgery with: :null_session
您还可以选择何时使用前置的参数运行此验证(此选项的默认值为false)。
protect_from_forgery with: :null_session, prepend: true
就像文件上说的
这是有用的,您希望您的伪造保护依赖于其他回调,如身份验证方法(Oauth vs Cookie auth)
https://stackoverflow.com/questions/41619177
复制相似问题