使用 @next/routing 进行路由
在适配器中使用 @next/routing 应用 Next.js 的路由匹配行为。
你可以使用 @next/routing,借助来自 onBuildComplete 的数据来复现 Next.js 的路由匹配行为。
import { resolveRoutes } from '@next/routing'
const pathnames = [
...outputs.pages,
...outputs.pagesApi,
...outputs.appPages,
...outputs.appRoutes,
...outputs.staticFiles,
].map((output) => output.pathname)
const result = await resolveRoutes({
url: new URL(requestUrl),
buildId,
basePath: config.basePath || '',
i18n: config.i18n,
headers: new Headers(requestHeaders),
requestBody, // ReadableStream
pathnames,
routes: routing,
invokeMiddleware: async (ctx) => {
// platform-specific middleware invocation
return {}
},
})
if (result.resolvedPathname) {
console.log('Resolved pathname:', result.resolvedPathname)
console.log('Resolved query:', result.resolvedQuery)
console.log('Invocation target:', result.invocationTarget)
}
resolveRoutes() 返回:
middlewareResponded:当中间件已经发送响应时,返回true(适配器不应调用入口点)。externalRewrite:当路由解析为外部重写目标时,返回一个URL。redirect:当请求应重定向时,返回一个包含url(URL)和status的对象。resolvedPathname:由 Next.js 路由选择的路由路径名。对于动态路由,这是匹配到的路由模板,例如/blog/[slug]。resolvedQuery:重写或中间件添加或替换搜索参数后的最终查询。invocationTarget:用于调用匹配路由的具体路径名和查询。resolvedHeaders:一个Headers对象,包含路由期间添加或修改的任何标头。status:由路由设置的 HTTP 状态码(例如来自重定向或重写规则)。routeMatches:从动态路由段中提取的命名匹配记录。
例如,如果 /blog/post-1?draft=1 匹配 /blog/[slug]?slug=post-1,那么 resolvedPathname 为 /blog/[slug],而 invocationTarget.pathname 为 /blog/post-1。