我有一个React Native应用,向Rails后端发出POST请求。即使我在protect_from_forgery with: :null_session
中插入了ApplicationController
。我发出的所有POST请求均失败,并且出现错误:
无法验证CSRF令牌的真实性
这是我向POST请求发出的Rails后端中的控制器之一:
class AddressesController < ApplicationController
def show
address = Address.find(params[:id])
end
def create
address = Address.new(address_params)
if address.save
render json: {status: 'address created successfully'}, status: :create
else
render json: { errors: address.errors.full_messages }, status: :bad_request
end
end
def address_params
params.require(:address).permit(:streetname, :zipcode, :city, :country)
end
end
在发送JSON POST请求时,我也曾尝试protect_from_forgery unless: -> { request.format.json? }
,但仍然遇到相同的错误。谁能提供其他解决方案?任何帮助将非常感激!预先感谢!
问题更新:
我遵循了这个人在link中所做的事情。我改为插入以下内容:
class ApplicationController < ActionController::Base
skip_before_action :verify_authenticity_token
end
现在,我没有收到“无法验证CSRF令牌真实性”错误,但仍然从终端中的服务器收到500(内部服务器错误)响应。由于某些原因未保存这些值。这是错误,我得到:
Address Create (0.4ms) INSERT INTO "addresses" ("streetname", "zipcode", "city", "country", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["streetname", "Imenstrade 39"], ["zipcode", "1082AK"], ["city", "Amsterdam"], ["country", "The Netherlands"], ["created_at", "2018-08-29 12:23:22.261020"], ["updated_at", "2018-08-29 12:23:22.261020"]]
↳ app/controllers/addresses_controller.rb:10
(2.2ms) commit transaction
↳ app/controllers/addresses_controller.rb:10
Completed 500 Internal Server Error in 12ms (Views: 0.2ms | ActiveRecord: 3.2ms)
答案 0 :(得分:0)
您可以用ActionController::API
代替ApplicationController
,我看到您写了status: :create
而不是status: :created
的语法错误