Hikaru Shindo
Hikaru Shindo

Reputation: 2923

serving an image file on NestJS always gets 404 error

I'm working on NestJS. I want to serve image files to clients. But it is not working.

Here is my project structure.

/MyProject
    /src
        app.module.ts
        ..
/uploads
    myimage.png

The image files are in /uploads. Furthermore, I have set the prefix url in the main.ts like this,

app.setGlobalPrefix('file');

Here is my ServeStaticModule inside app.module.ts,

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

When I try to access the image like,

http://localhost:5004/file/public/myimage.png or

http://localhost:5004/public/myimage.png or

http://localhost:5004/file/public/uploads/myimage.png or

http://localhost:5004/public/uploads/myimage.png or

I will get 404 error from the server.

The error is like this

{"message":"Cannot GET /file/public/myimage.png","error":"Not Found","statusCode":404}

Thanks for every helps.

Upvotes: 1

Views: 477

Answers (1)

R Z
R Z

Reputation: 21

I came across this issue just now. After i looked deep into it found that the issue could stem from the path. Before

    // Serve static files from the 'uploads' directory
  app.useStaticAssets(join(__dirname, '..', 'uploads'), {
    prefix: '/uploads/',
  });

And when i logged the path like console.log('Static file directory:', join(__dirname, '..', 'uploads')); logs as Static file directory: C:\Workspace\my-fkn-prj\uploads

The dist folder is the default directory where NestJS compiles your TypeScript code into JavaScript when you run the application using commands like npm run start:prod or npm run build. But not sure why its happens with npm run start:dev. Need to check into it.

This is why the join(__dirname, '..', 'uploads') path is resolving to C:\Workspace\my-fkn-prj\dist\uploads—it assumes the uploads folder is inside the dist directory.

After

     // Serve static files from the 'uploads' directory
  app.useStaticAssets(join(__dirname, '..', '..', 'uploads'), {
    prefix: '/uploads/',
  });

Upvotes: 0

Related Questions