watt
watt

Reputation: 879

Express - can't serve static files (404 error)

I came across many questions like these but it doesn't look like I'm doing anything wrong. The problem is that I can't get my static files to load.

Folder structure:

/client
    index.html
    /assets
        /css
            main.css
/server
    app.js

app.js:

var assetsPath = path.join(__dirname, '../client/assets');
app.use(express.static('assetsPath'));

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, '../client/' + 'index.html'));
});

app.listen(PORT, function () {
    console.log('\nListening on port 8080!');
});

index.html

<link rel="stylesheet" href="/css/main.css">

Yet when loading the page in the browser, I get 404 on http://localhost:8080/css/main.css

Is there anything missing?

Thank you!

PS: using express ^4.13.4 & node v5.10.1

Upvotes: 7

Views: 14261

Answers (2)

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

express.static accepts path to static files, so you can simplify with following line:

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

Upvotes: 3

QoP
QoP

Reputation: 28397

You got a typo in your express.static() function.

var assetsPath = path.join(__dirname, '../client/assets');
app.use(express.static('assetsPath'));

should be

var assetsPath = path.join(__dirname, '../client/assets');
app.use(express.static(assetsPath));

Upvotes: 8

Related Questions