从Node.js提供静态文件

时间:2013-04-22 02:54:47

标签: javascript node.js express

我正在尝试从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'));

2 个答案:

答案 0 :(得分:3)

如果您从根目录引用静态文件(即src='/some/path/to/file.js'),则该网址无关紧要。

使用静态路由的示例网站

目录结构

/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的使用。

答案 1 :(得分:0)

使用static()配置,Express已经至少能够找到/public/javascripts/whatever.js

但是,它取决于您的public文件夹是否与脚本位于同一目录中(由于在指定路径时使用了__dirname)。

如果是,则URL前缀/public应映射到./public的文件系统前缀(.__dirname),以便:

A URL of `/public/javascripts/whatever.js`
Maps to `./public/javascripts/whatever.js`