Fastify文件路由应用嵌套路由返回404问题解决
解决Fastify Generate项目嵌套路由404问题
原因分析
fastify generate默认的路由加载逻辑仅自动加载目录下的index.ts文件,嵌套目录内的其他命名文件不会被自动扫描注册,这就是/a/b/c.ts无法被识别的核心原因。
解决方案
方法1:手动注册嵌套路由文件
在父目录的index.ts中手动引入并注册目标路由文件。比如在/a/b/index.ts里添加:
import cRoute from './c.js' // 根据项目模块配置调整文件后缀 async function routes(fastify, options) { // 原有路由逻辑 fastify.get('/', async (request, reply) => { return { hello: 'b' } }) // 注册c.ts中的路由 fastify.register(cRoute) } export default routes
完成后访问/a/b/c即可匹配到c.ts里配置的路由。
方法2:自定义路由扫描规则
修改项目根目录入口文件(通常是app.ts)的路由加载配置,让Fastify自动扫描所有.ts路由文件:
import { fastifyAutoload } from '@fastify/autoload' import { fileURLToPath } from 'url' import { dirname, join } from 'path' import Fastify from 'fastify' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) async function build() { const fastify = Fastify({ logger: true }) fastify.register(fastifyAutoload, { dir: join(__dirname, 'routes'), // 设置文件匹配规则,包含所有.ts文件 include: /\.ts$/, // 可选:添加需要排除的文件规则 // exclude: /unwanted-file\.ts$/ }) return fastify }
配置后Fastify会自动扫描routes目录下所有.ts文件并注册路由。
方法3:调整文件命名结构
如果不想修改代码,可将c.ts重命名为/a/b/c/index.ts,默认的自动加载逻辑会识别该文件,此时访问/a/b/c即可匹配到该文件内的根路由;也可以把c.ts的路由逻辑直接合并到/a/b/index.ts中。
内容的提问来源于stack exchange,提问作者Alexander Suraphel
相关产品推荐
相关产品推荐

