typescript - 如何在 Nestjs 中使用 ServeStaticModule 访问多个子文件夹?
我有两个不同的模块用于 帖子 和 个人资料 的图片。所以我可以将图片保存在资产的两个不同的子文件夹中。
我的文件夹结构
现在的问题是我可以像这样在 Google 上访问 posts 文件夹的图片 http://localhost:3000/47b7a6b9c10.jpg
但是当我尝试访问 profile 文件夹中的图片,例如 http://localhost:3000/93d1a567c5.png 时,我得到的是空白页。并且看不到图片。
当前 app.module.ts 中的代码
PostsModule,
ProfileModule,
ServeStaticModule.forRoot(
{
rootPath: join(__dirname, '..', 'assets/posts'),
},
{
rootPath: join(__dirname, '..', 'assets/profile'),
},
),
我尝试过的事情
1-
ServeStaticModule.forRoot({
rootPath: join(__dirname, '..', 'assets/posts'),
}),
ServeStaticModule.forRoot({
rootPath: join(__dirname, '..', 'assets/profile'),
}),
2-
ServeStaticModule.forRoot(
{
serveRoot: '/assets',
rootPath: join(__dirname, '..', '/posts'),
},
{
serveRoot: '/assets',
rootPath: join(__dirname, '..', '/profile'),
},
),
3-
ServeStaticModule.forRoot({
serveRoot: '/assets',
rootPath: join(__dirname, '..', '/posts'),
}),
ServeStaticModule.forRoot({
serveRoot: '/assets',
rootPath: join(__dirname, '..', '/profile'),
}),
使用我当前的代码,我可以访问最初存在的子文件夹。比如,如果我将 assets/posts 替换为 assets/profile,我可以访问个人资料图片,反之亦然
答案#1
我已经找到了针对我特定情况的解决方案。术语 renderPath 起了作用。
解决方案
ServeStaticModule.forRoot(
{
rootPath: join(__dirname, '..', 'assets/posts'),
renderPath: '/posts',
},
{
rootPath: join(__dirname, '..', 'assets/profile'),
renderPath: '/profile',
},
),
要获取有关其他 ServeStaticModule API SPEC 选项 和 属性 的更多信息,请访问 https://www.npmjs.com/package/@nestjs/serve-static
