You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用加密ID发起Delete请求时出现405 Method Not Allowed错误

405 Method Not Allowed 错误原因及解决方法

问题背景

我为国家实体开发了一套CRUD功能,使用未加密的明文ID删除数据时操作正常,但使用Crypt加密后的ID发起Delete请求时,收到405 Method Not Allowed响应。

错误原因

核心问题出在Axios Delete请求的参数传递方式错误:

  • Axios的delete方法签名为axios.delete(url[, config]),第二个参数是配置对象,而非直接传递ID。
  • 明文ID场景下,因为ID是纯数字,请求URL仍为/cheek-system/static-countries/,服务器可能通过隐式匹配命中了路由;但加密后的ID是包含特殊字符的字符串,此时请求未正确携带路径参数,导致服务器找不到对应的DELETE路由,返回405(方法不允许)。

解决方案

1. 修正Axios请求的URL拼接方式

将ID(无论明文还是加密)正确拼接至URL路径中,符合RESTful路由规范:

修改destoy函数中的Axios请求代码:

function destoy(id, refrance) {
    // 正确拼接带ID的URL,用encodeURIComponent处理加密ID的特殊字符
    axios.delete(`/cheek-system/static-countries/${encodeURIComponent(id)}`)
        .then(function(response) {
            console.log(response);
            refrance.closest('tr').remove();
            showDeletingMessage(response.data);
        })
        .catch(function(error) {
            console.log(error);
            showDeletingMessage(error.response.data);
        });
}
  • 使用encodeURIComponent处理加密ID中的特殊字符(如+、/、=),避免URL解析错误。

2. 确保路由配置正确

Laravel路由需定义为带路径参数的DELETE路由,匹配请求URL:

// routes/web.php 或 routes/api.php
Route::delete('/cheek-system/static-countries/{country_enc_id}', [YourCountryController::class, 'destroy']);

3. 修正按钮的语法错误(明文ID场景笔误)

原明文ID按钮代码中有多余单引号,需修正:

@can('Delete-Country')
    <button type="button" onclick="confirmDestroy({{ $country->id }}, this)" class="btn btn-danger">
        <i class="fas fa-trash"></i>
    </button>
@endcan

4. 控制器方法保持现有逻辑

控制器的destroy方法无需修改,解密逻辑正常:

// Delete Static Country
public function destroy($country_enc_id)
{
    $this->checkUserAbility('Delete-Country');

    $isDeleted = DB::table('static_countries')
        ->where('id', Crypt::decrypt($country_enc_id))
        ->delete();
        
    return $isDeleted 
        ? response()->json([
            'icon' => 'success',
            'title' => 'Deleted',
            'text' => 'Static country deleted successfully'
        ], Response::HTTP_OK)
        : response()->json([
            'icon' => 'error',
            'title' => 'Failed',
            'text' => 'Failed to delete static country'
        ], Response::HTTP_BAD_REQUEST);
}

内容的提问来源于stack exchange,提问作者Ahmad Almabhoh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:39:45