【问题标题】:Next.js routing with "next-connect" for subroutesNext.js 路由与子路由的“next-connect”
【发布时间】:2021-11-18 16:39:44
【问题描述】:

在我的Next.js 项目中,我使用next-connect 包创建了类似route->middleware->endpoint 的表达模式。

我有这个路线模式:

/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.Docs: 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 的所有请求,而不是为每个子路由创建一个文件 欢迎任何建议或帮助

【问题讨论】:

    标签: reactjs next.js next-router next-connect


    【解决方案1】:

    您收到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 钩子或data-fetching 方法之一,访问动态parameter

    // pages/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 ${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,
    }
    

    【讨论】:

    • 您在server.js 文件中定义subRoutemainRoute。但是我的项目中没有自定义服务器。我正在使用 Next.js 的基于目录的路由。您能否提供一个示例实现。
    • 我以为你是自定义服务器,我不是真的意思 server.js,我只是复制了你在问题中使用的 sn-p,所以我可以将 top-5-cheat 作为 id 查询传递@ABDULLOKHMUKHAMMADJONOB
    • @ABDULLOKHMUKHAMMADJONOB。我的回答解决了问题吗?
    猜你喜欢
    • 2021-02-25
    • 2021-08-06
    • 2019-02-07
    • 2022-01-04
    • 2020-06-06
    • 2021-10-17
    • 2020-08-12
    • 2021-12-22
    • 2020-09-08
    相关资源
    最近更新 更多