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

NextJS中如何通过单个文件监听多个API端点?

NextJS API Catch-All路由未触发的解决方法

核心问题:路由文件命名错误

NextJS Pages Router的catch-all动态路由必须用[...path].ts(三个点),你当前用的[*path].ts不符合框架路由规则,这是代码从未触发的直接原因。只有[...path]才能匹配/api/之后的任意层级路径(比如/api/playlist/2331、/api/account/12)。

修正后的完整代码

将文件名改为[...path].ts,替换代码如下:

import axios from 'axios';
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { method, body, query } = req;
  // path是数组格式,比如/api/playlist/2331的path为['playlist', '2331']
  const pathSegments = Array.isArray(query.path) ? query.path : [query.path];
  const targetPath = pathSegments.join('/');

  if (!targetPath) {
    return res.status(400).json({ error: '无效的请求路径' });
  }

  // 过滤掉query中的path字段,避免传递给上游服务器重复参数
  const { path, ...cleanQuery } = query;

  try {
    const apiUrl = `http://localhost:3001/api/${targetPath}`;
    const response = await axios({
      method,
      url: apiUrl,
      data: body,
      params: cleanQuery,
    });

    // 直接透传上游服务器的响应
    res.status(response.status).json(response.data);
  } catch (error) {
    console.error('转发请求失败:', error);
    const errorMessage = axios.isAxiosError(error) ? error.response?.data?.message || '请求失败' : '未知错误';
    res.status(500).json({ error: errorMessage });
  }
}

关键修正点说明

  • 路由匹配:[...path].ts确保捕获所有/api/下的子路径请求
  • 路径拼接:将数组格式的path字段拼接为完整的上游请求路径
  • 参数清理:移除query中的path字段,避免把路由参数误当作查询参数传递
  • 异步优化:用async/await替代Promise回调,代码更简洁易维护
  • 响应透传:直接返回上游服务器的状态码和原始响应数据,保证请求一致性
  • 类型支持:引入NextJS的API请求/响应类型,获得TypeScript的类型提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:12:24