如何在NestJS中提供静态文件?上传目录访问404报错排查
NestJS静态资源404问题解决
问题背景
项目根目录存在uploads文件夹,期望通过http://localhost:7777/uploads/audio/85/0.mp3、http://localhost:7777/uploads/movie/85/0.mp4这类带/uploads前缀的路径访问静态文件,但返回404错误,错误信息如下:
{"statusCode": 404,"message": "ENOENT: no such file or directory, stat 'G:\myproject\uploads\index.html'"}
已按Nest官方文档配置ServeStaticModule但未达到预期效果。
现有配置代码
App.module
import { ServeStaticModule } from '@nestjs/serve-static'; import { join } from 'path'; @Module({ imports: [ ServeStaticModule.forRoot({ rootPath: join(__dirname, '../../../', 'uploads'), }), UsersModule ] }) export class AppModule {}
Main.ts
import { NestFactory } from '@nestjs/core'; import { AppModule } from './App/app.module'; import { ConfigService } from '@nestjs/config'; import { ValidationPipe } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); const configService = app.get(ConfigService); const port = configService.get('PORT'); app.enableCors(); app.useGlobalPipes(new ValidationPipe()); await app.listen(port); } bootstrap();
问题原因
当前ServeStaticModule仅配置了rootPath,将uploads文件夹设为静态资源根目录,此时正确访问路径应为http://localhost:7777/audio/85/0.mp3(不带/uploads前缀)。但你需要保留/uploads前缀作为访问入口,缺少对应的serveRoot配置项。
解决方案
- 添加
serveRoot配置
修改App.module中的ServeStaticModule配置,指定静态资源的访问前缀:
ServeStaticModule.forRoot({ rootPath: join(__dirname, '../../../', 'uploads'), serveRoot: '/uploads', // 配置访问前缀 })
- 验证
rootPath正确性
临时在App.module中添加日志打印,确认路径是否指向正确的uploads文件夹:
console.log('静态资源根路径:', join(__dirname, '../../../', 'uploads'));
启动项目后查看控制台输出,若路径错误,调整../../../的层级(根据App.module.ts的实际位置修改向上跳转的目录层数)。
- 重启服务测试
修改配置后重启NestJS服务,再次访问http://localhost:7777/uploads/audio/85/0.mp3即可正常获取文件。
内容的提问来源于stack exchange,提问作者Руслан Лысенко
相关产品推荐
相关产品推荐

