darby
darby

Reputation: 167

Express.js just won't serve static files

I am trying desperately to get it working that my express server serves statics files but I just can't get it to work... I already tried multiple attempts at solving it but none of it worked.

So my folder structure is the following:

App
- Web
-- public
--- images
--- css
-- Server.js

The code from my server is the following

const express = require('express');
const app = express();
app.use('/static', express.static('./public'));

const server = app.listen(80, function() {
    const host = server.address().address;
    const port = server.address().port;

    console.log(`Server is running on ${host}:${port}`);
});

It just won't serve the files.. No matter how I change the usage of the public folder. I already tried with path.join and __dirname but none of it worked. I only get the express error Cannot GET /static ...

Upvotes: 0

Views: 2213

Answers (2)

Ali Ibraheem
Ali Ibraheem

Reputation: 73

For me I was serving the static content right with: app.use(express.static('public')) But I was accessing this content in a wrong way: you don't need to put public folder in path. http://localhost:3000/images/user.png is correct. http://localhost:3000/public/images/user.png is wrong

Upvotes: 2

Christian Fritz
Christian Fritz

Reputation: 21364

This can happen when the current working directory is not what you think it is and hence ./public doesn't resolve to the right path. The safer way to do this is to use __dirname, the directory of the current file:

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

Upvotes: 3

Related Questions