【发布时间】:2013-11-10 04:35:07
【问题描述】:
我的客户端应用程序将 JSON 编码的 POST 发送到 Rails 服务器,但服务器显示 406 错误并且不响应 json。
UsersController 创建
# POST /users
# POST /users.json
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
Rails 控制台:
Started POST "/users.json" for 127.0.0.1 at 2013-05-21 16:38:47 +0100
Processing by Devise::RegistrationsController#create as JSON
Parameters: {"user"=>{"name"=>"", "available"=>"true", "email"=>"", "sex"=>"male", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}
WARNING: Can't verify CSRF token authenticity
(0.2ms) begin transaction
User Exists (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = '' LIMIT 1
(0.2ms) rollback transaction
Completed 406 Not Acceptable in 773ms (ActiveRecord: 6.1ms)
谁能帮帮我?
【问题讨论】:
-
我建议的一件事是关闭 CSRF 令牌真实性。为此,请转到呈现 json 的控制器并添加
skip_before_filter :verify_authenticity_token。像使用任何其他过滤器一样进行相应调整。这当然是假设您无法在将 JSON 发送到 Rails 的应用程序中生成 CSRF 令牌。 -
关闭 cross-site request forgery protection 对我来说不是个好主意。
标签: ruby-on-rails json