gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:49:56 27 4
gpt4 key购买 nike

我有一个目录结构

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com