configure node express to serve static bower_compo

2020-01-27 10:25发布

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?

7条回答
别忘想泡老子
2楼-- · 2020-01-27 10:54

I'm using:

$ npm -version && node -v
2.11.3
v0.12.7

And my app.js has this defining bower_components as a static path:

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

In my Jade template, I reference jquery and bootstrap like so:

doctype html
html
    head
        title= title
        link(href='bootstrap/dist/css/bootstrap.min.css', rel='stylesheet')
        link(href='bootstrap/dist/css/bootstrap-theme.min.css', rel='stylesheet')
    body
        block content

    script(type='text/javascript', src='jquery/dist/jquery.js')
    script(type='text/javascript', src='bootstrap/dist/js/bootstrap.js')

I'm running Windows 7 (x64).

Hope this helps someone.

查看更多
登录 后发表回答