reactjs request.query在Next.js 13 API路由中未定义

jaql4c8m  于 2023-10-17  发布在  React
关注(0)|答案(1)|浏览(143)

下面是我使用的代码结构的简化版本:
app/api/events/route.js中:

import Event from "@models/Event";
import { connectToMongoDB } from "@utils/database/connectToMongoDB";

export default async (req, res) => {
  console.log(req);
  const { filterBy, ...filters } = req.query;
  // Rest of the code...
}

下面是上述端点在app/(root)/page.jsx中的实现:

export async function getServerSideProps() {
  const response = await fetch(`/api/events?filterBy=status&status=Live`);
  // Rest of the code...
}

我得到以下错误:

- error TypeError: Cannot destructure property 'filterBy' of 'request.query' as it is undefined.

下面是我登录到控制台的请求对象:

NextRequest [Request] {
  [Symbol(realm)]: {
    settingsObject: { baseUrl: undefined, origin: [Getter], policyContainer: [Object] }
  },
  [Symbol(state)]: {
    method: 'GET',
    localURLsOnly: false,
    unsafeRequest: false,
    body: null,
    client: { baseUrl: undefined, origin: [Getter], policyContainer: [Object] },
    reservedClient: null,
    replacesClientId: '',
    window: 'client',
    keepalive: false,
    serviceWorkers: 'all',
    initiator: '',
    destination: '',
    priority: null,
    origin: 'client',
    policyContainer: 'client',
    referrer: 'client',
    referrerPolicy: '',
    mode: 'cors',
    useCORSPreflightFlag: false,
    credentials: 'same-origin',
    useCredentials: false,
    cache: 'default',
    redirect: 'follow',
    integrity: '',
    cryptoGraphicsNonceMetadata: '',
    parserMetadata: '',
    reloadNavigation: false,
    historyNavigation: false,
    userActivation: false,
    taintedOrigin: false,
    redirectCount: 0,
    responseTainting: 'basic',
    preventNoCacheCacheControlHeaderModification: false,
    done: false,
    timingAllowFailed: false,
    headersList: HeadersList {
      cookies: null,
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: [Array]
    },
    urlList: [ URL {} ],
    url: URL {
      href: 'http://[::1]:3000/api/events?filterBy=status&status=Live',
      origin: 'http://[::1]:3000',
      protocol: 'http:',
      username: '',
      password: '',
      host: '[::1]:3000',
      hostname: '[::1]',
      port: '3000',
      pathname: '/api/events',
      search: '?filterBy=status&status=Live',
      searchParams: URLSearchParams { 'filterBy' => 'status', 'status' => 'Live' },
      hash: ''
    }
  },
  [Symbol(signal)]: AbortSignal { aborted: false },
  [Symbol(abortController)]: AbortController { signal: AbortSignal { aborted: false } },
  [Symbol(headers)]: HeadersList {
    cookies: null,
    [Symbol(headers map)]: Map(20) {
      'accept' => [Object],
      'accept-encoding' => [Object],
      'accept-language' => [Object],
      'cache-control' => [Object],
      'connection' => [Object],
      'cookie' => [Object],
      'host' => [Object],
      'sec-ch-ua' => [Object],
      'sec-ch-ua-mobile' => [Object],
      'sec-ch-ua-platform' => [Object],
      'sec-fetch-dest' => [Object],
      'sec-fetch-mode' => [Object],
      'sec-fetch-site' => [Object],
      'sec-fetch-user' => [Object],
      'upgrade-insecure-requests' => [Object],
      'user-agent' => [Object],
      'x-invoke-output' => [Object],
      'x-invoke-path' => [Object],
      'x-invoke-query' => [Object],
      'x-middleware-invoke' => [Object]
    },
    [Symbol(headers map sorted)]: [
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array]
    ]
  },
  [Symbol(internal request)]: {
    cookies: RequestCookies { _parsed: [Map], _headers: [HeadersList] },
    geo: {},
    ip: undefined,
    nextUrl: NextURL { [Symbol(NextURLInternal)]: [Object] },
    url: 'http://localhost:3000/api/events?filterBy=status&status=Live'
  }
}

我在Next.js应用程序中向API路由传递查询参数时遇到了这个问题。我在Next.js页面组件中使用getServerSideProps,并从API路由获取数据,但服务器端似乎没有正确接收查询参数。
我尝试使用useEffect而不是getServerSideProps,问题仍然存在。

cygmwpex

cygmwpex1#

首先,你的路由处理程序的签名是错误的,它甚至可以在应用程序路由器中工作,因为你试图应用在页面路由器中使用的相同逻辑。
路由处理程序必须是命名的导出,例如GETPOST等。此外,这里有一个完整的工作路由处理程序访问URL搜索参数的片段:

import { type NextRequest } from 'next/server'
 
export function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const query = searchParams.get('query')
  // query is "hello" for /api/search?query=hello
}

这一切都是假设你 * 实际上 * 使用应用路由器,正如你的路径从/app开始所暗示的那样。

相关问题