middleware->endpoint模式使用 next-connect包裹。 我有这个路线模式: /api/tours-6ren">
gpt4 book ai didi

reactjs - Next.js 路由 "next-connect"用于子路由

转载 作者:行者123 更新时间:2023-12-04 12:27:40 30 4
gpt4 key购买 nike

在我的 Next.js项目,我创建了一个 express ,如 route->middleware->endpoint模式使用 next-connect包裹。
我有这个路线模式:

/api/tours 

/api/tours/:id

/api/tours/top-5-cheap

/api/tours/stats

/api/tours/monthly-plan
...
在我的 pages/api/tours/index.js我添加了一个路由来捕获 api/tours 和所有其他子路由,如 api/tours/top-5-cheap。
根据文档,这应该有效。但只有 api/tours 工作正常,任何对 api/tours/subroute 的请求都会给出 page not found error.文档: next-connect
import nc from 'next-connect'
const mainRoute = nc({ attachParams: true })

const subRoute1 = nc().use(mid1).get((req, res) => { res.end("api/tours/top-5-cheap") });
const subRoute2 = nc().use(mid2).use(mid3).post(endpoint2);
const subRoute3 = nc().use(mid4).use(mid5).use(mid6).get((req, res) => { res.end("api/tours/monthly-plan") })

mainRoute
.use("/top-5-cheap", subRoute1)
.use("/stats", subRoute2)
.use("/monthly-plan", subRoute3)
.get((req, res) => { res.end("api/tours") })

export default mainRoute
我希望能够从 pages/api/index.js 捕获对 api/tours 和 api/tours/subroute 的所有请求文件而不是为每个子路由创建一个文件
欢迎任何建议或帮助

最佳答案

您收到了 404: Page not found错误,因为该页面不存在。 Next.JS路由方法,表示api/tours/top-5-cheap会去/pages/api/top-5-cheap.js .如果它不存在,它会返回一个错误。
注意 :您可以在没有 next-connect 的情况下执行此操作使用基于 Next.JS 文件的路由系统打包。
next-connect这是我的两个可能的解决方案

  • 创建一个新文件并将名称括在方括号中 ( [] ) 使其成为 dynamic route .
  • └── pages
    └── api
    └── tours
    ├── index.js
    └── [id].js
    并使用 useRouter Hook 或其中之一 data-fetching 方法,访问动态 parameter
    // pages/api/tours/[id].js
    import { useRouter } from 'next/router';

    const Post = () => {
    const router = useRouter();
    return <p>Post: {router.query.id}</p>
    }
  • 您可以向基本路由发送请求并将子路由作为查询传递
  • www.example.com/api/tours?id=top-5-cheap
    // pages/api/tours/index.js
    export default function (req, res) {
    // sub-route id will be passed in params object
    // const id = req.params.id // top-5-cheap; ...
    res.send(`Requested ${req.query.id} api page`)
    }
    next-connect您不能将 Next.JS 服务器与基于文件的路由和 next-connect 包一起使用,因此您必须使用自定义服务器。
    Using a Custom Server 上阅读官方文档.
    请记住,您必须 disable the file-based routing 像你想要的那样工作。
    // next.config.js
    module.exports = {
    useFileSystemPublicRoutes: false,
    }

    关于reactjs - Next.js 路由 "next-connect"用于子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69331211/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com