Laravel+Axios生产环境DELETE请求报405 Method Not Allowed求助
解决Laravel生产环境DELETE请求返回405 (Method Not Allowed)的问题
以下是针对该问题的排查和解决步骤:
1. 验证Laravel路由配置与缓存
- 确认
routes/web.php中是否正确定义了DELETE路由,格式应类似:
注意路由参数名(如Route::delete('/posts/{post}/destroy', [PostController::class, 'destroy'])->name('posts.destroy');{post})需与控制器方法接收的参数一致。 - 生产环境执行路由缓存清理命令:
Laravel生产环境默认会缓存路由,若修改路由后未更新缓存,会导致新路由无法生效。php artisan route:clear php artisan route:cache
2. 确保CSRF令牌与请求头正确
- 检查前端是否正确获取CSRF令牌:确保页面头部包含meta标签:
并在fetch请求中正确读取该令牌:<meta name="csrf-token" content="{{ csrf_token() }}">const token = document.querySelector('meta[name="csrf-token"]').content; - 在fetch请求中添加
Accept: application/json头,帮助Laravel正确识别请求类型:fetch('/posts/'+ postid + '/destroy', { method: 'DELETE', headers: { 'X-CSRF-Token': token, 'Accept': 'application/json' } });
3. 检查AWS EC2的Web服务器配置
若使用Nginx:
- 确保站点配置文件中正确转发请求到Laravel的
index.php,避免拦截DELETE/PUT方法:
修改配置后重启Nginx:server { listen 80; server_name ec2-18-181-225-61.ap-northeast-1.compute.amazonaws.com; root /var/www/html/public; index index.php; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; } }sudo systemctl restart nginx
若使用Apache:
- 确认启用了
mod_rewrite模块:sudo a2enmod rewrite - 确保项目根目录的
.htaccess文件包含Laravel默认的重写规则:
重启Apache:<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule>sudo systemctl restart apache2
4. 使用绝对URL发起请求
避免相对路径可能带来的路径解析问题,通过Laravel的url()辅助函数生成绝对URL:
在Blade模板中给删除按钮传递完整URL:
<span data-id="{{ $post->id }}" data-url="{{ url('/posts/'.$post->id.'/destroy') }}">删除</span>
然后在JS中使用该URL:
const postUrl = span.dataset.url; fetch(postUrl, { method: 'DELETE', headers: { 'X-CSRF-Token': token, 'Accept': 'application/json' } });
5. 切换为Axios发起请求(你提到使用Axios开发)
Axios会自动处理CSRF令牌的携带,配置更简便:
// 确保已引入Axios axios.delete(`/posts/${postid}/destroy`) .then(() => { span.parentNode.parentNode.remove(); const count = ul.childElementCount; if (count === 0) { ul.insertBefore(noLi, ul.firstChild); } }) .catch(err => console.error(err));
内容的提问来源于stack exchange,提问作者Programing Account
相关产品推荐
相关产品推荐

