我正在尝试从 Node.js
提供静态文件,我遇到的唯一问题是,如果我继续进入子路径,如下所示:
localhost:3000/foo/bar/baz/quux
然后我必须增加相同的次数,如下所示:
../../../../public/javascripts/whatever.js
正如你所看到的,这真的很烦人,有没有一种方法可以让 Express v3 知道,这样我就可以执行 /public/javascripts/whatever.js
而不必采取行动?提前致谢
这是我当前的 Express 静态中间件`
app.use("/public", express.static(__dirname + '/public'));
最佳答案
如果您从根目录引用静态文件(即 src='/some/path/to/file.js'
),则 url 应该不重要。
使用静态路由的示例网站
目录结构
/public
/css/style.css
/js/site.js
/vendor/thoughtbrain/js/awesome-town.js
/views/view.html
/app.js
view.html
<!DOCTYPE html>
<html>
<head>
<!-- These files are served statically from the '/public' directory... -->
<link href="/css/style.css" rel="stylesheet" >
<script src="/js/site.js"></script>
<!-- ... while this is "mounted" in virtual '/public' -->
<script src="/public/js/awesome-town.js"></script>
</head>
<body><p>Express</p></body>
</html>
app.js
var express = require('express'),
http = require('http'),
path = require('path'),
app = express();
// Remember: The order of the middleware matters!
// Everything in public will be accessible from '/'
app.use(express.static(path.join(__dirname, 'public')));
// Everything in 'vendor/thoughtbrain' will be "mounted" in '/public'
app.use('/public', express.static(path.join(__dirname, 'vendor/thoughtbrain')));
app.use(express.static(path.join(__dirname, 'views')));
app.all('*', function(req, res){
res.sendfile('views/view.html')
});
http.createServer(app).listen(3000);
运行此应用程序后,
http://localhost:3000
和
http://localhost:3000/foo/bar/baz/quux
两者都提供view.html,并且所有引用的资源都会解析。
Express Framework 有一节介绍 static middleware here 的使用.
关于javascript - 从 Node.js 提供静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16138732/