【问题标题】:CakePHP 4 - Ajax POST request return forbidden 403 with security disabledCakePHP 4 - Ajax POST 请求返回禁止 403 并禁用安全性
【发布时间】:2021-07-12 06:10:02
【问题描述】:

我正在尝试为学校项目制作一个简单的 Pokemon 目录,并且我想将 Ajax 用于“添加到购物车”按钮。然而,即使我添加了 CakePHP 官方文档中提到的内容以禁用安全性,我仍然不断收到“加载资源失败:服务器响应状态为 403(禁止)”。

我知道这个问题被问了很多次,但实际上找不到 4.x 的有效答案。我的错误在哪里?提前感谢您的回复

Ajax 函数:

function ajaxAddToBasket(poke_id){
    $.post("<?= $this->Url->build(['controller' => 'Paniers', 'action' => 'Addtobasket']) ?>",
        {
            pokemon_id: poke_id,
        },
        function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        }
    );
}

控制器:

public function initialize(): void
{
    parent::initialize();
    $this->loadComponent('Security');
}

public function beforeFilter(EventInterface $event)
{
    parent::beforeFilter($event);
    $this->Security->setConfig('unlockedActions', ['addtobasket']);
}

public function addtobasket()
{

    $pokemon_id = $this->request->getData('pokemon_id');
    $user_id = $this->request->getSession()->read('user_id');

    if($pokemon_id != null && is_nan($pokemon_id)){
          /** Some to-dos here **/
    }
}

【问题讨论】:

  • 请检查您的错误/调试日志 (/logs/) 以了解实际触发该错误/响应的详细信息。安全组件通常会触发400 错误,而不是403,后者是对 CSRF 中间件的提示。

标签: cakephp cakephp-4.x


【解决方案1】:

您需要在标头中发送 X-CSRF-Token。这就是我的 Ajax-Request 的样子:

$.ajax({
  url: "/Paniers/Addtobasket/",
  type: "POST",
  data: {"pokemon_id":poke_id},
  headers: {
      'X-CSRF-Token': <?= json_encode($this->request->getAttribute('csrfToken')); ?>,
  },
  success: function (data) {
    console.log(data);
  },
  error: function(error, message) {
    console.log(error, message);
  }
}); 

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多