在我的Next.js
项目中,我使用next-connect
包创建了一个类似route->middleware->endpoint
的express模式
我有这样的路由模式:
/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/suboute的请求都会给出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/suboute的所有请求,而不是为每个子路由创建一个文件欢迎提出任何建议或帮助
您得到一个404: Page not found
错误,因为页面不存在。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`)
}
Withnext-connect
你不能使用基于文件的路由和next-connect包的Next.JS服务器,所以你必须使用自定义服务器。
阅读Using a Custom Server
的官方文档。
请记住,您必须使用disable the file-based routing
才能像您希望的那样工作。
// next.config.js
module.exports = {
useFileSystemPublicRoutes: false,
}