Home > database >  Serving Static Files in Express not working
Serving Static Files in Express not working

Time:01-12

I want:

I want to access static files in /uploads folder in the root of my project by visiting the URL (http://localhost:4002/uploads/test.jpg)

The issue:

I am unable to access static files in uploads folder. Visiting the URL (http://localhost:4002/uploads/test.jpg) gives: Cannot GET /uploads/test.jpg

According to a tutorial I follow and to official docs it should work the way I have implemented it...

I have tried three methods:

  app.use(express.static('uploads'))
  app.use('/uploads', express.static('uploads')) 
  app.use('/uploads', express.static(path.join(__dirname, 'uploads')))

GitHub Repo image

CodePudding user response:

In your github repo, there's a tests.jpg, but NOT a test.jpg in the uploads folder so thus the URL in your question http://localhost:4002/uploads/test.jpg refers to a file that is not present in the uploads directory .

If you change the URL to match the filename that actually exists in the uploads folder, then

app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

should work with the URL

http://localhost:4002/uploads/tests.jpg
  •  Tags:  
  • Related