I have a directory structure
projectName
| - bower_components/
| - public/
| - css
| - js
| - index.html
| - Gruntfile.js
| - package.json
| - bower.json
| - app.js
I would like to start my app and serve index.html
with node. So in app.js
I have:
var express = require('express');
var port = process.env.PORT || 3000;
var app = express();
app.configure(function(){
// Serve up content from public directory
app.use(express.static(__dirname + '/public'));
app.use(app.router);
app.use(express.logger());
});
app.listen(port, function(){
console.log('Express server listening on port ' + port);
});
At the bottom of index.html
I have:
<script src="../bower_components/jquery/jquery.js"></script>
<script src="../bower_components/d3/d3.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="bower_components/spin.js/spin.js"></script>
<script src="bower_components/mustache/mustache.js"></script>
When I start the server, index.html
shows up but none of the above libraries load. I get the error (404):
GET http://localhost:3000/bower_components/jquery/jquery.js 404 (Not Found) localhost/:32
GET http://localhost:3000/bower_components/d3/d3.js 404 (Not Found) localhost/:33
GET http://localhost:3000/bower_components/bootstrap/dist/js/bootstrap.js 404 (Not Found) localhost/:34
GET http://localhost:3000/bower_components/spin.js/spin.js 404 (Not Found) localhost/:35
GET http://localhost:3000/bower_components/mustache/mustache.js 404 (Not Found)
How can I serve the files from bower_components?
I use this setup:
So any Bower components are loaded from HTML like this:
And any other client-side JS/CSS (in
public/
) are loaded like this:Had the same problem after moving bower_components into another folder. This has helped me to understand what was going on. The docs were useful: https://github.com/expressjs/serve-static
and I put this code into my node/express app.js file:
This is from index.html
and in app.js
which is a correct path in my case.
Bower can be configured using JSON in a
.bowerrc
file.Add an
.bowerrc
file with the following contents at the root of your project with the contents.This will place the bower components your are refering to in the correct library and you will not need the extract static directory in express.
Change your directory structure to :
And in
index.html
do following changes:Or another way is to turn your
bower_components
folder to severed as static content. (you can injectstatic middleware
multiple times for express)Add the following in app congfig to express. Then your config code looks like:
And in this case your directory structure remains the same. Hope this helps.
Happy coding.. :)
This also works for me:
Make sure you have reset your local server or make sure you are running nodemon for seeing your changes!
You should use
Note the usage of (path.join) which is different from @robertklep answer
Here is a note from Another SO questions which according to me captures it very well