在我的Next.js项目中,我使用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-廉价。根据文档,这应该是可行的。但是只有api/tours才能正常工作,任何对api/tours/subroute的请求都会给出一个page not found error.文档:下一次连接
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的所有请求,而不是为每个子路由创建一个文件,欢迎任何建议或帮助。
发布于 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。
└── 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服务器及其基于文件的路由和下一个连接包,因此您必须使用自定义服务器。
阅读Using a Custom Server上的官方文档。
请记住,您必须disable the file-based routing才能按您的意愿工作。
// next.config.js
module.exports = {
useFileSystemPublicRoutes: false,
}https://stackoverflow.com/questions/69331211
复制相似问题