1

I have been reading and implementing so many solutions but nothing seems to work.

I am using nestjs ServeStatic for their official doc and following question from StackOverflow.

but nothing seems to work.

So far my Code

app.module.ts

import { ServeStaticModule } from '@nestjs/serve-static/dist/serve-static.module';
import { join } from 'path';

@Module({
  imports: [ 
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'public'),
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})

My Folder Structure

/Source
  |-public
  |--img.jpg
  |-src
  |--app.module.ts
  |--app.controller.ts
  |--main.ts

Trying to access the file through

http://localhost:3000/public/img.jpg

Error:

[Nest] 3320   - 06/17/2021, 5:24:42 PM   [ExceptionsHandler] ENOENT: no such file or directory, stat 'F:\code\dist\public\index.html' +3898ms
Error: ENOENT: no such file or directory, stat 'F:\code\dist\public\index.html'

The Question I have been following

Question 1

Question 2

Doc

xitas
  • 1,136
  • 3
  • 23
  • 47

2 Answers2

13

The problem was that it was looking for the file in dist folder. to resolve we have to get one level up and after that, it was getting the only index.html so for that we have to add serveRoot

Code

import { ServeStaticModule } from '@nestjs/serve-static/dist/serve-static.module';
import { join } from 'path';

@Module({
  imports: [ 
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', '../public'), // added ../ to get one folder back
      serveRoot: '/public/' //last slash was important
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
xitas
  • 1,136
  • 3
  • 23
  • 47
5

You'r probably missing the prefix option in your main.ts.

app.useStaticAssets(join(__dirname, '..', 'public'), {
  prefix: '/public',
});

You don't need to use the ServeStaticModule in your app.module.ts.

ServeStaticModule.forRoot({
    rootPath: join(__dirname, '..', 'public'),
    // serveRoot: 'public'
}),

You can also remove this from your main.ts.

app.use(express.static(__dirname + 'public'));
app.use('/', express.static('../public'));
Hugo Sohm
  • 2,872
  • 4
  • 23
  • 40