ERROR: POST http://localhost:8765/users/delete/delete8 403 (Forbidden)

ERROR: POST http://localhost:8765/users/delete/delete8 403 (Forbidden)

我在用蛋糕php4。试图添加一些 sweetalert。单击删除按钮时会弹出 Sweetalert,但当我单击确认删除时,它并没有删除数据。

template/layout/Users/index.php

<table>
<tr>
    <th>Username</th>
    <th>Usertype</th>
    <th>Created</th>
    <th>Action</th>
</tr>

<?php foreach ($users as $user) : ?>
    <tr>
        <td>
            <?= $this->Html->link($user->username, ['action' => 'view', $user->slug]); ?>
        </td>
        <td>
            <?= $this->Html->tag('span', $user->utype) ?>
        </td>
        <td>
            <?= $user->created->format(DATE_RFC850); ?>
        </td>
        <td>
            <?= $this->Html->link('Edit', ['action' => 'edit', $user- 
               >slug]); ?> /
            
            <a href="#" class="delete" data-slug="<?=$user->slug? 
               >">Delete</a>
           
        </td>
    </tr>
<?php endforeach; ?>

template/layout/Users/index.php

<script>

deletes = document.getElementsByClassName('delete');
Array.from(deletes).forEach((element) => {
  element.addEventListener("click", (e) => {
    let ajax_url = $(e.target).attr('data-slug');
    
    Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
      if (result.isConfirmed) {
          $.ajax({
            method: 'POST',
            url: '/users/delete/'+ ajax_url,
            beforeSend: function(xhr){
                xhr.setRequestHeader(
                    'X-CSRF-Token',
                    <?= json_encode($this->request- 
                       >getParam('_csrfToken')); ?>
                );
            },
            success: function(response){
                if(response){
                    Swal.fire(
                        'Deleted!',
                        'Your file has been deleted.',
                        'success'
                    )
                }
                else {
                    Swal.fire({
                      icon: 'error',
                      title: 'Oops...',
                      text: 'No data deleted',
                 })
      }
            },
            error: function(e){
                console.log('error', e);
            }
          })
       
      } 
    })
  })
})

我的删除方法如下UsersController.php

UsersController.php

public function delete($slug)
{
    $this->request->allowMethod(['post', 'delete']);
    $user = $this->Users->findBySlug($slug)->firstorFail();
    if ($this->Users->delete($user)) {
        $this->Flash->success("Deleted Successfully");
        return $this->redirect(['action' => 'index']);
    }
    $this->Flash->error('Unable to Delete user');
    return $this->redirect(['action' => 'index']);
}

路由文件在这里 config/route.php

  <?php

   use Cake\Http\Middleware\CsrfProtectionMiddleware;
   use Cake\Routing\Route\DashedRoute;
   use Cake\Routing\RouteBuilder;


  $routes->setRouteClass(DashedRoute::class);

  $routes->scope('/', function (RouteBuilder $builder) {

   $builder->connect('/', ['controller' => 'Pages', 'action' => 
'display', 'home']);
  
  $builder->connect('/users/delete/{slug}', ['controller' => 'Users', 
'action' => 'delete']);

  $builder->connect('/pages/*', 'Pages::display');

  $builder->fallback();

});

我确定是 CSRF 令牌。尝试替换

<?= json_encode($this->request->getParam('_csrfToken')); ?>

<?= json_encode($this->request->getAttribute('csrfToken')); ?>

此外,我不确定您的“beforeSend: function(xhr)”,您可以在此处查看有效的 ajax 调用示例: