0

我遇到了 Rails 5 的一个非常奇怪的问题。我有两个控制器,第一个 asusers_controller和第二个 as api/v1/users_controller。这两个控制器都有一个register动作。我正在尝试向这两个控制器发布表单。此表单创建如下,

 <%= form_tag('v2/register/user', {id: "add-user-form", class: "jiffle-form", role: "form"}) do%>
   #form body
   <%= submit_tag("Resigter", data: {i18n: "register"}, class:  "btn btn-lg btn-block btn-blue", id: "add-user", type: "submit") %>
<% end %>

路线

post "register" => "users#create", :as => "user_registeration_submit"
post "v2/register/user" => "api/v1/users#create"

当我使用/registerurl 提交表单时,它会成功处理。但是,当我使用v2/register/userurl 提交表单时Can't verify CSRF token authenticity出现错误。

参数

Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ADNTIp9alRB/ujRhkoqNuDkzdW6ANfcl/MbPjGLwVd6nwVuG5oi+uVhE9MeZo+1MeyKLbwZYNV31Vy/VH3M2bg==", "sfdc_token"=>"",
 "email"=>"[FILTERED]", "first_name"=>"kjl", "last_name"=>"jk", "contact_no"=>"894892849", "company_name"=>"j", "title"=>"kj",
 "internal_366vagan2"=>"", "consent"=>"true",
 "commit"=>"Register"}

api/v1/users_controller当我使用 ajax 在请求中使用X-CSRF-TOKEN标头提交表单时,它工作正常。

我在哪里进行更改以使我的 api/v1 控制器工作?

4

1 回答 1

1

你可以简单地写在 application_controller.rb

   protect_from_forgery with: :exception, unless: -> { request.format.json? }

并在 routes.rb 文件中设置默认格式为 json

但更好的方法:

在您的情况下,您必须创建两个命名空间,一个用于处理 API 响应,另一个用于处理 FORM。相应地在 routes.rb 文件中使用命名空间。并且相应地还有两个不同的基本控制器,它们继承自 ApplicationController。

对于 API

class Api::V1::ApplicationController < ApplicationController
   protect_from_forgery with: :exception, unless: -> { request.format.json? }
end

并在 routes.rb 文件中设置默认格式为 json

 resources :tasks, defaults: {format: :json}

对于表格视图

使用默认设置,或

class Admin::AdminController < ApplicationController
   protect_from_forgery with: :exception
end
#In this case, comment it from main application_controller.rb file:protect_from_forgery with: :exception

注意:这里 Admin 和 Api 是两个命名空间。而且 routes.rb 文件看起来像:

#For admin
namespace :admin do

end 

#For Api
namespace :api do
    scope module: :v1 do

    end
end 

希望它会工作:)

于 2019-04-27T19:40:51.247 回答