javascript - 配置 Node express 服务静态 bower_components?

标签 javascript node.js express bower

我有一个目录结构

projectName
    | - bower_components/
    | - public/
        | - css
        | - js
        | - index.html
    | - Gruntfile.js
    | - package.json
    | - bower.json
    | - app.js

我想启动我的应用程序并使用 Node 提供 index.html。所以在 app.js 我有:

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);
});

index.html 的底部我有:

<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>

当我启动服务器时,index.html 出现了,但是上面的库都没有加载。我收到错误(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) 

如何从 bower_components 提供文件?

最佳答案

我使用这个设置:

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

所以任何 Bower 组件都是从 HTML 中加载的,如下所示:

<script src="/bower_components/..."></script>

并且任何其他客户端 JS/CSS(在 public/ 中)都是这样加载的:

<script src="/js/..."></script>

关于javascript - 配置 Node express 服务静态 bower_components?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821773/

相关文章:

javascript - Ajax DELETE 查询返回意外对象

javascript - 如何检查对象的参数是否获取其他变量?

node.js - Heroku 仅显示 MERN 应用程序的后端。我怎样才能解决这个问题?

node.js - 快速应用程序使用

node.js - Node.js 中的基本函数调用

javascript - 如何纠正从 jsFiddle 到 HTML 的 no wrap(head) JavaScript 以使其正常工作

javascript - 将一个子元素向左对齐,第二个子元素向右对齐 extjs

javascript - 为什么我不能用字符串更新 MySQL?

javascript - Express.js JWT 授权成功后始终返回默认 404 错误

node.js - 使用 include in (Sequelize) 在不嵌套对象的情况下显示属性