【jquery-rails】Ajax로 POST하면 「Can't verify CSRF token authenticity.」가 발생한다
문제점
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.rbRails.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)
Reference
이 문제에 관하여(【jquery-rails】Ajax로 POST하면 「Can't verify CSRF token authenticity.」가 발생한다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/NaokiIshimura/items/5824ae274d08af1de031
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
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.rbRails.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)
Reference
이 문제에 관하여(【jquery-rails】Ajax로 POST하면 「Can't verify CSRF token authenticity.」가 발생한다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/NaokiIshimura/items/5824ae274d08af1de031
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
$ rails g scaffold user name:string
$ rails g controller static_pages home
gem 'jquery-rails'
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require jquery3
//= require jquery_ujs
//= require_tree .
Rails.application.routes.draw do
root 'static_pages#home'
resources :users
end
<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>
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)
Reference
이 문제에 관하여(【jquery-rails】Ajax로 POST하면 「Can't verify CSRF token authenticity.」가 발생한다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/NaokiIshimura/items/5824ae274d08af1de031텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)