【jquery-rails】AjaxでPOSTすると「Can't verify CSRF token authenticity.」が発生する

# 問題点

AjaxでJSONをPOSTしてモデルオブジェクトを保存しようとすると「Can't verify CSRF token authenticity.」(422エラー)が発生する

## POST受信時のサーバログ

```shell-ession
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`を追記した

## 修正前

```js:app/assets/javascripts/application.js
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require jquery3
//= require_tree .
```

## 修正後

```js: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](https://github.com/NaokiIshimura/qiita-rails-Post_with_Ajax_in_JS)

![ajax10.png](https://qiita-image-store.s3.amazonaws.com/0/141934/0907b909-77d6-7d51-b8cb-e2235e2b090b.png)

```shell-session:事前準備
$ rails g scaffold user name:string
$ rails g controller static_pages home
```

```rb:Gemfile(抜粋)
gem 'jquery-rails'
```

```js:app/assets/javascripts/application.js
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require jquery3
//= require jquery_ujs
//= require_tree .
```

```rb:config/routes.rb
Rails.application.routes.draw do
  root 'static_pages#home'
  resources :users
end
```

```erb+html: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成功時のブラウザログ
![ajax11.png](https://qiita-image-store.s3.amazonaws.com/0/141934/3d723898-c4c1-35e6-22e4-5a7848894c36.png)


## POST成功時のサーバログ
```shell-ession
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)
```