【问题标题】:Nextjs API endpoint on rootroot 上的 Nextjs API 端点
【发布时间】:2022-11-22 19:45:34
【问题描述】:

我在 URL 根目录上有一个页面,这是一个用 React 构建的下一页。

现在我也想在 root 上公开一个 API 端点。

`http://localhost:3000/` > points to React page
`http://localhost:3000/foo` > points to the Next API endpoint
`http://localhost:3000/bar` > points to the **same** Next API endpoint
`http://localhost:3000/anything` > points to the **same** Next API endpoint

是否可以重写 API 端点的根路径?如果是,如何?

【问题讨论】:

标签: javascript reactjs typescript next.js


【解决方案1】:

如果我正确理解你的问题,你正在寻找动态路线。

你可以有

http://localhost:3000/[slug]

以便,

http://localhost:3000 // will hit index.tsx
http://localhost:3000/foo // will hit pages/foo (because it's defined)
http://localhost:3000/bar // will hit pages/bar (because it's defined)
http://localhost:3000/{anything} // will hit [slug].tsx (because it's not defined)

但在这种情况下,您可以从查询参数中获取不匹配的路由。

import { useRouter } from 'next/router'

// Component ...
  const router = useRouter()
  const {
    query: { slug }
  } = router

您的文件夹结构看起来像

/pages
 /foo
  index.tsx
 /bar
  index.tsx
 /[slug]
  index.tsx
 index.tsx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 2021-12-27
    • 2019-06-05
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    相关资源
    最近更新 更多