【问题标题】:Error: CSRF token mismatch in cakephp 3.6.10错误:cakephp 3.6.10 中的 CSRF 令牌不匹配
【发布时间】:2018-08-09 23:23:02
【问题描述】:

我正在做一个简单的选择更改。但是我遇到了以下错误:

Error: [Cake\Http\Exception\InvalidCsrfTokenException] CSRF token mismatch.

这是我在控制器上的功能:

public function municipios() {

$this->viewBuilder()->layout('ajax');
$this->LoadModel('Municipios');
$subregion = $this->request->getData['subregion_id'];


    $municipios = $this->Municipios->find('list',[
        'limit' => 200,

        'conditions' => ['Municipios.subregion_id' => $subregion],
        'contain' => ['Subregiones']

       ]);

    $this->set(compact('municipios'));
    $this->set('_serialize', 'municipios');

}

这是我的 jquery ajax:

$(document).ready(function () {
    $("#subregion-id").bind("change",
    function (event) {
      $.ajax({
    async:true,
    data: $("#subregion-id").serialize(),
    dataType:"html",
    success:
    function (data, textStatus) {
      $("#municipio-id").html(data);
      },
      type:"post", url:"\/lavaderos\/municipios"});
  return false;
      });
  });

我阅读了需要令牌但我不知道该怎么做的文档。

该代码在 3.5.x 中工作正常,但在 3.6.x 中没有

谢谢

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    您可以通过 ajax 调用中的特殊 X-CSRF-Token 标头向您发送 CSRF 令牌来解决此问题。 https://book.cakephp.org/3.0/en/controllers/components/csrf.html

    $(document).ready(function () {
        $("#subregion-id").bind("change",
        function (event) {
          $.ajax({
        async:true,
        data: $("#subregion-id").serialize(),
        dataType:"html",
        beforeSend: function (xhr) { // Add this line
            xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
        },  // Add this line
        success:function (data, textStatus) {
          $("#municipio-id").html(data);
        },
          type:"post", url:"\/lavaderos\/municipios"});
      return false;
          });
      });
    

    您可以为您的 ajax 操作禁用 CSRF 组件[Cakephp 不推荐],例如:

    public function beforeFilter(Event $event) {
         if (in_array($this->request->action, ['ajaxEdit'])) {
             $this->eventManager()->off($this->Csrf);
         }
     }
    

    【讨论】:

    • @JoseRafaelCamejo 太好了。请接受答案。这将对其他人有所帮助。
    • @JoseRafaelCamejo 第一个解决方案对我不起作用。看来$('[name="_csrfToken"]').val() 没有任何价值。它在console.log()中返回undefined
    • 如果它返回未定义,您可以将其添加到您的视图中:<input type="hidden" name="_csrfToken" value="<?= $this->request->getParam('_csrfToken'); ?>" />
    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2017-06-06
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多