0
0

More than 3 years have passed since last update.

CakePHPで実装しているAPIをJQueryのAJAXから呼び出す。

Posted at

やりたこと

CakePHPで実装しているAPIをJQueryのAJAXから呼び出す。
単純に呼び出すとCSRF token from either the request body or request headers did not match or is missingが発生する。
CSRFチェックを停止するのは避けたい。

環境(今回の作業に関連ないものも記載)

  • cakephp4.1.2
  • jQuery3.5.1

実装

templateファイルにcsrfToken用のinputを配置する。

xxx.php
<input type="hidden" name="_csrfToken" autocomplete="off" value="<?= $this->request->getAttribute('csrfToken') ?>">

それをjsファイルから取得してAPIを呼び出す。

xxx.js
$.ajax({
    type: 'post',
    url: '/xxxs/add',
    headers: { 'X-XSRF-TOKEN' : $('input[name="_csrfToken"]').val() },
    beforeSend: function (xhr) {
        xhr.setRequestHeader('X-CSRF-Token', $('input[name="_csrfToken"]').val());
    },
    dataType: 'json',
    data: {
        "_csrfToken":$('input[name="_csrfToken"]').val()
    },
    async: true,
    cache: false,
}).then(function (data) {
})

参照

0
0
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
0
0