問題点
AjaxでJSONをPOSTしてモデルオブジェクトを保存しようとすると「Can't verify CSRF token authenticity.」(422エラー)が発生する
POST受信時のサーバログ
Started POST "/users" for 127.0.0.1 at 2018-05-13 11:49:53 +0900
Processing by UsersController#create as JSON
Parameters: {"user"=>{"name"=>"hogehoge"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)
解決方法
app/assets/javascripts/application.jsに//= require jquery_ujs
を追記した
修正前
app/assets/javascripts/application.js
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require jquery3
//= require_tree .
修正後
app/assets/javascripts/application.js
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require jquery3
//= require jquery_ujs
//= require_tree .
サンプルコード
AjaxでJSONをPOSTしてモデルオブジェクトを保存するサンプルコード
実装
NaokiIshimura/qiita-rails-Post_with_Ajax_in_JS
事前準備
$ rails g scaffold user name:string
$ rails g controller static_pages home
Gemfile(抜粋)
gem 'jquery-rails'
app/assets/javascripts/application.js
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require jquery3
//= require jquery_ujs
//= require_tree .
config/routes.rb
Rails.application.routes.draw do
root 'static_pages#home'
resources :users
end
app/views/static_pages/home.html.erb
<input type="text" id="name">
<button id="create">post</button>
<script>
$("#create").click(function () {
var data = {
"user":
{
name: $("#name").val()
}
};
$.ajax({
type: "post",
url: "<%= users_path %>",
data: JSON.stringify(data),
contentType: 'application/json',
dataType: "json",
success: function (data) {
console.log("success");
console.log(data);
$("#name").val("");
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
</script>
POST成功時のブラウザログ
POST成功時のサーバログ
Started POST "/users" for 127.0.0.1 at 2018-05-13 11:50:04 +0900
Processing by UsersController#create as JSON
Parameters: {"user"=>{"name"=>"hogehoge"}}
(0.1ms) begin transaction
↳ app/controllers/users_controller.rb:32
User Create (0.5ms) INSERT INTO "users" ("name", "created_at", "updated_at") VALUES (?, ?, ?) [["name", "hogehoge"], ["created_at", "2018-05-13 02:50:04.381871"], ["updated_at", "2018-05-13 02:50:04.381871"]]
↳ app/controllers/users_controller.rb:32
(2.5ms) commit transaction
↳ app/controllers/users_controller.rb:32
Rendering users/show.json.jbuilder
Rendered users/_user.json.jbuilder (0.7ms)
Rendered users/show.json.jbuilder (2.3ms)
Completed 201 Created in 19ms (Views: 11.6ms | ActiveRecord: 3.1ms)