首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于子路由的带有“下一步连接”的Next.js路由

用于子路由的带有“下一步连接”的Next.js路由
EN

Stack Overflow用户
提问于 2021-09-26 01:42:19
回答 1查看 1.7K关注 0票数 4

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

我有这样的路线模式:

代码语言:javascript
复制
/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-廉价。根据文档,这应该是可行的。但是只有api/tours才能正常工作,任何对api/tours/subroute的请求都会给出一个page not found error.文档:下一次连接

代码语言:javascript
复制
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/ than / subroute的所有请求,而不是为每个子路由创建一个文件,欢迎任何建议或帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-02 08:23:42

您将得到一个404: Page not found错误,因为页面不存在。Next.JS路由方法,意味着api/tours/top-5-cheap将转到/pages/api/top-5-cheap.js。如果它不存在,它会返回一个错误。

注意事项:您可以不使用基于Next.JS文件的路由系统的next-connect包来完成此操作。

next-connect

以下是我可能的两种解决方案

  • 创建一个新文件,并将名称括在括号([])中,使其成为dynamic route

代码语言:javascript
复制
└── pages
    └── api
        └── tours
            ├── index.js
            └── [id].js

并使用useRouter钩子或data-fetching方法之一访问动态parameter

代码语言:javascript
复制
// pages/tours/[id].js
import { useRouter } from 'next/router';

const Post = () => {
  const router = useRouter();
  return <p>Post: {router.query.id}</p>
}
  • 您可以向基路由发送请求,并将子路由作为查询传递。

代码语言:javascript
复制
www.example.com/api/tours?id=top-5-cheap

代码语言:javascript
复制
// 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服务器及其基于文件的路由和下一个连接包,因此您必须使用自定义服务器。

阅读Using a Custom Server上的官方文档。

请记住,您必须disable the file-based routing才能按您的意愿工作。

代码语言:javascript
复制
// next.config.js
module.exports = {
  useFileSystemPublicRoutes: false,
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69331211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档