zhangyuang / ssr

A most advanced ssr framework support React17/React18/Vue2/Vue3 on Earth that implemented serverless-side render specification.
http://doc.ssr-fc.com/
MIT License
2.59k stars 283 forks source link

动态路由前缀 #335

Closed nead3009 closed 1 month ago

nead3009 commented 1 month ago

最近在研究使用这个框架,在nextjs中,可以通过目录名来动态实现,拿个最常见的使用场景,比如国际化路由前缀,该怎么实现呢,比如: www.xxx.com/zh www.xxx.com/zh/about www.xxx.com/zh/news/detail?id=122

能否给个实现思路或简单代码示例?谢谢~

zhangyuang commented 1 month ago

ssr 框架同样可以通过目录名来生成路由。例如创建pages/zh/render.vue 等于/zh 路由, /pages/zh/about/render.vue等于 /zh/about 路由。

也可以使用固定的config.prefix或者动态prefix 使得不需要创建zh文件夹,直接给路由层面添加统一的前缀即可

nead3009 commented 1 month ago

嗯,刚看了文档中动态prefix的示例,但是没太看懂,比如我要实现news.controller.ts,改造前是这样

@Controller('news')
export  class AppController {
//...省略
@Get('list')
async handlerIndex (@Req() req: Request, @Res() res: Response): Promise<void> {
    const ctx = {
      request: req,
      response: res,
      apiService: this.apiService
    }
    const stream = await render(ctx, {
      stream: true,
      onError: (err) => {
        console.log('ssr error', err)
        render(ctx, {
          stream: true
        }).then(csrStream => {
          csrStream.pipe(res)
        })
        return null
      },
      onReady () {
        // for normal ssr end
        stream.pipe(res)
      }
    })
}
@Get('detail:id')
async handlerDetail (@Req() req: Request, @Res() res: Response): Promise<void> {
    const ctx = {
      request: req,
      response: res,
      apiService: this.apiService
    }
    const stream = await render(ctx, {
      stream: true,
      onError: (err) => {
        console.log('ssr error', err)
        render(ctx, {
          stream: true
        }).then(csrStream => {
          csrStream.pipe(res)
        })
        return null
      },
      onReady () {
        // for normal ssr end
        stream.pipe(res)
      }
    })
}
}

那如果想通过动态prefix支持国际化路由,我该怎么写呢

zhangyuang commented 1 month ago

配置动态路由前缀为prefix:/zh后也就是浏览器打开localhost:3000/zh/list 等于访问到pages/list/render.vue组件,也就是前端router的/list路由。zh为基准path无需在前端路由中添加

nead3009 commented 1 month ago

嗯,原理是这样,但是我上面所写的news.controller.ts的根路由不是/,而是/news 【news.controller.ts的根路径是@controller('news') 不是@controller('/')】,接合动态路由示例和我理解的,那是不是如果想支持动态prefix是不是原来的多个控制器都要统一写在index.controller.ts中,并且包含不同handler不同语言handler,比如/zh/news => handlerZhNews, /zh/news/detail => handlerZhNewsDetail.....

zhangyuang commented 1 month ago

路由支持通配符,自行查询对应的Node.js框架文档

nead3009 commented 1 month ago

帮我看看,我配了prefix,为啥会报 With Path: /zh/news search component failed image

zhangyuang commented 1 month ago

你写在了onError里面。。。先看懂示例代码的含义

nead3009 commented 1 month ago

哦,忘记上面的了.........