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

如何在NextApiRequest中获取HTTP请求的Query参数?

解决Next.js API路由中无法获取query参数的问题

你的问题核心是请求对象类型使用错误,Next.js的两种路由系统(Pages Router和App Router)对请求参数的处理方式完全不同,下面分情况给出解决方案:

情况1:使用传统Pages Router(文件位于pages/api/目录下)

如果你的API文件放在pages/api目录,理论上req.query应该直接可用。若出现undefined,可以尝试以下方式:

  • 确保正确导入类型:
    import type { NextApiRequest, NextApiResponse } from 'next'
    
  • 若仍有问题,手动解析URL获取参数:
    import { parse } from 'url';
    import type { NextApiRequest, NextApiResponse } from 'next'
    
    export async function GET(req: NextApiRequest, res: NextApiResponse) {
      if (req.method !== 'GET') {
        res.setHeader('Allow', ['GET']);
        return res.status(405).end('Method Not Allowed');
      }
    
      const { query } = parse(req.url, true);
      const type = query.type as string;
      const cusID = "**************";
      const pmID = "******************";
    
      try {
        if (type === 'paymentMethod') {
          const paymentMethod = await stripe.customers.retrievePaymentMethod(cusID, pmID);
          console.log(paymentMethod);
          return res.status(200).json(paymentMethod);
        } else if (type === 'customer') {
          const customer = await stripe.customers.retrieve(cusID);
          console.log('Customer:', customer);
          return res.status(200).json(customer);
        } else {
          return res.status(400).json({ error: "No valid query parameter provided" });
        }
      } catch (error) {
        console.error(error);
        return res.status(500).json({ error: "Internal Server Error" });
      }
    }
    

情况2:使用App Router(文件位于app/api/[route]/route.ts)

如果你的API文件是Next.js 13+新增的App Router结构,不能使用NextApiRequest/NextApiResponse,需要改用NextRequest,并通过nextUrl.searchParams获取查询参数:

import { NextRequest, NextResponse } from 'next/server';

export async function GET(req: NextRequest) {
  // 直接通过searchParams获取type参数
  const type = req.nextUrl.searchParams.get('type');
  
  const cusID = "**************";
  const pmID = "******************";

  try {
    if (type === 'paymentMethod') {
      const paymentMethod = await stripe.customers.retrievePaymentMethod(cusID, pmID);
      console.log(paymentMethod);
      return NextResponse.json(paymentMethod, { status: 200 });
    } else if (type === 'customer') {
      const customer = await stripe.customers.retrieve(cusID);
      console.log('Customer:', customer);
      return NextResponse.json(customer, { status: 200 });
    } else {
      return NextResponse.json({ error: "No valid query parameter provided" }, { status: 400 });
    }
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}

关键说明

你代码中req.query为undefined的最可能原因是:在App Router路由文件中误用了Pages Router的NextApiRequest类型,两者的请求对象结构完全不同,App Router下不存在req.query属性,必须通过req.nextUrl.searchParams获取查询参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:38:17