错误:POST http://localhost:8765/users/delete/delete8 403(禁止)

时间:2021-05-04 05:54:18

标签: javascript php jquery cakephp cakephp-4.x

我正在使用 cakephp4。试图添加一些甜蜜。单击删除按钮时会弹出 Sweetalert,但当我单击确认删除时,它不会删除数据。

模板/布局/用户/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; ?>

模板/布局/用户/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']);
}

路由文件在这里 配置/路由.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();

});

1 个答案:

答案 0 :(得分:0)

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

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

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

我也不确定你的“beforeSend: function(xhr)”,你可以在这里看到一个有效的ajax调用示例:

https://stackoverflow.com/a/67253585/15256337

相关问题