【jquery-rails】Ajax로 POST하면 「Can't verify CSRF token authenticity.」가 발생한다

4816 단어 아약스Rails

문제점



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)

좋은 웹페이지 즐겨찾기