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

NextJS+Hono+AWS S3中DELETE接口报405错误,POST可正常运行

解决NextJS + Hono DELETE接口405错误的方案

1. 检查NextJS API路由的方法导出

这是最常见的触发原因:在NextJS App Router中,每个HTTP方法都需要显式导出对应的处理函数。如果你的app/api/media/route.ts只导出了GET和POST,未导出DELETE,NextJS会直接拒绝DELETE请求并返回405。

修改你的路由文件:

import { Hono } from 'hono'
import { handle } from 'hono/vercel'

const mediaS3App = new Hono()

// 你的DELETE接口逻辑
mediaS3App.delete('/delete', async (c) => {
  try {
    const fileName = c.req.query('fileName');
    if (!fileName) return c.json({error: 'File name required.'}, 400);
    
    const result = await getSignedURL(fileName, 'DELETE');
    if (result.failure) return c.json({error: result.failure}, 401);
    
    return c.json({url: result.success?.url});
  } catch (error) {
    console.error('Server error:', error);
    return c.json({error: 'An unexpected error occurred.'}, 500);
  }
})

// 必须显式导出所有需要支持的HTTP方法
export const GET = handle(mediaS3App)
export const POST = handle(mediaS3App)
export const DELETE = handle(mediaS3App) // 这行是关键,不能省略!

2. 处理CSRF保护拦截

NextJS默认会对非GET/HEAD/OPTIONS的请求进行CSRF校验,如果你的DELETE请求未携带正确的CSRF令牌,会被拦截并返回405。

修改客户端请求,添加CSRF令牌到请求头:

import { cookies } from 'next/headers'

// ...
await Promise.all(fileSelected.map(async (fileName) => {
  try {
    // 获取CSRF令牌(若使用NextAuth,令牌格式为`token|hash`,取前半部分即可)
    const csrfToken = cookies().get('next-auth.csrf-token')?.value?.split('|')[0] || '';
    
    const DELURLResponse = await fetch(`/api/media/delete?fileName=${encodeURIComponent(fileName)}`, {
      method: 'DELETE',
      headers: {
        'X-CSRF-Token': csrfToken,
        'Content-Type': 'application/json',
      },
    });

    const DELSignedURL = await DELURLResponse.json();
    // 后续删除逻辑保持不变...
  } catch (error) {
    console.error('An error occurred during the deletion:', error);
  }
}))

如果是自定义CSRF配置,确保请求头携带了NextJS期望的令牌字段(默认是X-CSRF-Token)。

3. 验证路由匹配与CORS配置

  • 确认Hono路由路径与客户端请求路径完全匹配:你的Hono路由是/delete,挂载在/api/media下,实际接口路径为/api/media/delete,从报错信息看这部分是匹配的。
  • 若涉及跨域,在next.config.js中配置允许DELETE方法:
const nextConfig = {
  async headers() {
    return [
      {
        source: '/api/media/:path*',
        headers: [
          { key: 'Access-Control-Allow-Methods', value: 'GET, POST, DELETE, OPTIONS' },
          { key: 'Access-Control-Allow-Origin', value: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000' },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

按照以上步骤排查,基本可以解决DELETE方法的405错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 02:00:21