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

Next.js v13中间件Rewrite/Redirect在API请求中失效问题排查

Next.js 13 中间件对API请求失效及JSON解析错误解决方案

问题核心

中间件对页面请求的redirect/rewrite正常,但API请求时失效,前端fetch解析响应时出现JSON格式错误——本质是API请求最终返回了HTML内容(比如重定向后的登录页),而非预期的JSON响应。

排查与解决步骤

1. 补全中间件的API路径匹配规则

确保中间件的matcher配置覆盖所有API路由,否则中间件根本不会拦截API请求:

// middleware.js
export const config = {
  matcher: [
    '/', // 页面路径
    '/api/:path*' // 必须添加这行,匹配所有API子路径
  ]
}

2. 区分API与页面请求的处理逻辑

不要给API请求返回页面重定向,而是返回JSON格式的错误响应:

// middleware.js
import { NextResponse } from 'next/server'

export function middleware(request) {
  const isApiRequest = request.nextUrl.pathname.startsWith('/api/')
  const isAuthenticated = () => { /* 你的鉴权逻辑 */ }

  // API请求:未授权时返回JSON错误
  if (!isAuthenticated() && isApiRequest) {
    return new NextResponse(JSON.stringify({ error: '未授权' }), {
      status: 401,
      headers: { 'Content-Type': 'application/json' }
    })
  }

  // 页面请求:未授权时重定向到登录页
  if (!isAuthenticated() && !isApiRequest) {
    return NextResponse.redirect(new URL('/login', request.url))
  }

  return NextResponse.next()
}

3. 前端fetch请求增加异常处理

先校验响应状态和内容类型,避免直接解析非JSON响应:

// page.js 中的提交逻辑
async function submitForm() {
  try {
    const res = await fetch('/api/your-endpoint', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData)
    })

    if (!res.ok) {
      const contentType = res.headers.get('content-type')
      if (contentType?.includes('application/json')) {
        const error = await res.json()
        console.error('API错误:', error)
      } else {
        // 拿到HTML响应时,直接跳转到登录页
        window.location.href = '/login'
      }
      return
    }

    const data = await res.json()
    // 处理正常响应
  } catch (err) {
    console.error('请求失败:', err)
  }
}

4. 验证API路由本身的正确性

暂时禁用中间件,直接请求API接口,确认返回的是标准JSON格式,排除API自身的问题。

内容的提问来源于stack exchange,提问作者Enes Gülcü

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:07:12