2
2

More than 1 year has passed since last update.

CakePHP4でajaxが403になる件

Posted at

問題

CakePHP4でajaxすると403になる。

原因

「config/routes.php」に全体のCSRFチェックの処理がデフォルトで入っているため、
フォーム以外からのPOSTはエラーになる。

対策1

以下を参照
http://tech.zhu-weichen.com/2020/09/15/164917/6/

対策2

最初は対策1をとっていたが、トークンを送信する形にしてみた。

html
<input type="hidden" name="_csrfToken" id="_csrfToken" autocomplete="off" value="<?= $this->request->getAttribute('csrfToken') ?>">
javascript
    $.ajax({
      url: "test/ajax_test",
      dataType: "json",
      type: "post",
      data: {"_csrfToken":$("#_csrfToken").val()},
      success: function(data) {}
    });
TestController.php
function ajaxTest() {
    // 取得
    $data = $this->request->getData();
    // 返却
    return $this->response->withType('application/json')->withStringBody(json_encode($data))
}
2
2
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
2
2