Ruby on rails 如何在Rails6中使用Webpack提交ajax表单?获取ActionController::InvalidAuthenticationToken错误
全部 下面是关于GoRails的视频,介绍如何使用action cable制作聊天应用程序。在视频中,我相信Rails 5正在被使用,但是,我想用Rails 6试试 到目前为止一切都很顺利。安装了Bootstrap和jQuery,并正确配置了我的Ruby on rails 如何在Rails6中使用Webpack提交ajax表单?获取ActionController::InvalidAuthenticationToken错误,ruby-on-rails,ajax,forms,ujs,Ruby On Rails,Ajax,Forms,Ujs,全部 下面是关于GoRails的视频,介绍如何使用action cable制作聊天应用程序。在视频中,我相信Rails 5正在被使用,但是,我想用Rails 6试试 到目前为止一切都很顺利。安装了Bootstrap和jQuery,并正确配置了我的environments.js文件。太棒了。然后,在我们添加action cable之前,我开始讨论这个部分,我们将聊天室表单设置为remote:true 我不明白为什么我的表单仍然试图以HTML而不是JS的形式提交。最重要的是,我得到了一个Action
environments.js
文件。太棒了。然后,在我们添加action cable之前,我开始讨论这个部分,我们将聊天室表单设置为remote:true
我不明白为什么我的表单仍然试图以HTML而不是JS的形式提交。最重要的是,我得到了一个ActionController::InvalidAuthenticityToken
错误
下面是我如何设置表格的:
<%= simple_form_for [@chatroom, Message.new], remote: true, html: { id: 'message-input' } do |f| %>
<%= f.input :body, label: false, input_html: { rows: 1, autofocus: true } %>
<% end %>
不知道该怎么办。我在谷歌上搜索到了这一点,但我不确定它是否完全适用:
任何帮助都将不胜感激 当请求
POST
请求时,rails会检查authenticity\u令牌
在javascript的请求中,您需要添加一个标题:'X-CSRF-Token':csrfToken
您可以使用以下JS获取csrfToken
:
const csrfToken = document.querySelector('[name="csrf-token"]').getAttribute('content');
另一种解决方案是禁用verify\u authenticity\u token
,您可以将其添加到应用程序\u controller.rb中禁用它,也可以将其添加到特定于控制器的:
skip_before_action :verify_authenticity_token
因此,我不得不使用form_with
,而不是form_for
,以便将其作为JS处理。我想
的form\u正在被弃用
我的表单现在如下所示:
<%= form_with(model: [@chatroom, Message.new]) do |f| %>
<%= f.text_field :body %>
<% end %>
<%= form_with(model: [@chatroom, Message.new]) do |f| %>
<%= f.text_field :body %>
<% end %>
Started POST "/chatrooms/1/messages" for ::1 at 2019-10-18 20:15:14 -0500
Processing by MessagesController#create as JS
Parameters: {"authenticity_token"=>"xPBQ+4LOS5aMa7PQ3HEGXAMX6wIIEfQ0Izy/xUqUtleK4mB18IYxC4mOcIoiS5M+FGm6J/WEYMdbM4IVPojScw==", "message"=>{"body"=>"test 5"}, "chatroom_id"=>"1"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Chatroom Load (0.3ms) SELECT "chatrooms".* FROM "chatrooms" WHERE "chatrooms"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/messages_controller.rb:19:in `set_chatroom'
(0.1ms) BEGIN
↳ app/controllers/messages_controller.rb:12:in `create'
Message Create (0.7ms) INSERT INTO "messages" ("chatroom_id", "user_id", "body", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["chatroom_id", 1], ["user_id", 1], ["body", "test 5"], ["created_at", "2019-10-19 01:15:14.619853"], ["updated_at", "2019-10-19 01:15:14.619853"]]
↳ app/controllers/messages_controller.rb:12:in `create'
(5.6ms) COMMIT
↳ app/controllers/messages_controller.rb:12:in `create'
Redirected to http://localhost:3000/chatrooms/1
Completed 200 OK in 17ms (ActiveRecord: 7.6ms | Allocations: 4690)