如果您从根目录(即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
视图.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>
应用程序.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 有一节介绍静态中间件的使用。