matheushf matheushf - 1 year ago 236
Node.js Question

bower_components not loading with express static

I'm making an express app using bower, but somehow the bower_components folder isn't found. I've searched here, tried all solutions, but nothing worked.

In my server.js I have:


// Set static files
app.use('/bower_components', express.static(__dirname + '/bower_components'));

In the index


<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css" /></script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>

And what I get:

GET http://localhost:3000/bower_components/bootstrap/dist/css/bootstrap.css
(index):85 GET http://localhost:3000/bower_components/jquery/dist/jquery.js
(index):86 GET http://localhost:3000/bower_components/angular/angular.js

Cannot GET /bower_components/bootstrap/dist/css/bootstrap.css

It works if I remove the "/bower_components" prefix from the tags, and change in server to this:


<link rel="stylesheet" href="/bootstrap/dist/css/bootstrap.css" />

Answer Source

This should be caused by bower_components folder outside your server folder. Modify your code at server/app.js to this:

var path = require('path');

app.use('/bower_components', express.static(path.dirname(__dirname) + '/bower_components'));

Here i'm using the dirname() funtion from the path built in nodejs package to get the parent folder of your server folder.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download