5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelでajax(POST)を使うときに気をつけること

Last updated at Posted at 2019-01-04

#0.前提条件
環境:cloud9、laravel 5.3、PHP7.0
resorces/view/~.blade.php からajaxでpostするときにこんなエラーメッセージがでた。

POST https://laravel-knhj-test/test 419 (unknown)

どうやらLaravelではデフォルトでPOST通信には全てCSRFトークンをつけてやる必要があり、ajaxでの通信でもつける必要があるらしい。
#1.XMLHttpRequestにCSRFトークンを入れる

JavascriptでCSRFトークンをリクエストヘッダーに入れるためには以下の記載が必要になる。

index.blade.php
<meta name="csrf-token" content="{{ csrf_token() }}">
(中略)
<script>
    var formdata = new FormData();
      formdata.append('name', 'knhj');

     var xhttpreq = new XMLHttpRequest();
     xhttpreq.onreadystatechange = function () {
        if(xhttpreq.readyState == 4 && xhttpreq.status == 200) { alert(xhttpreq.responseText);}
        if(xhttpreq.readyState == 4 && xhttpreq.status != 0) {alert("アップロード完了");}
     };
     var token = document.getElementsByName('csrf-token').item(0).content; 
     xhttpreq.open("POST", "ポスト先", true);
     xhttpreq.setRequestHeader('X-CSRF-Token', token); 
     xhttpreq.send(formdata);
</script>

ポイントは2点。
①metaタグでCSRFトークンを作成して、getElementsByNameでトークンを取得する。
②openした後(xhttpreq.openをxhttpreq.setRequestHeaderより後に書くとエラーが出る)、setRequestHeaderメソッドを使ってCSRFトークンをリクエストヘッダーに入れる。

#2.参考URL
http://kayakuguri.github.io/blog/2017/12/06/laravel-ajax-csrf/
https://stackoverflow.com/questions/28524485/xmlhttprequest-throwing-invalidsateerror-saying-object-state-must-be-opened
https://readouble.com/laravel/5.5/ja/csrf.html#csrf-x-csrf-token
https://re-engines.com/2018/05/31/javascript-csrf/
https://stackoverflow.com/questions/46466167/laravel-5-5-ajax-call-419-unknown-status
http://repenguin.hateblo.jp/entry/2016/09/26/124056

5
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?