javascript - 从 Node.js 提供静态文件

标签 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'));

最佳答案

如果您从根目录引用静态文件(即 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/

相关文章:

javascript - 如何使用 wordpress 在点击时播放 GIF(如 9GaG.com)?

node.js - 通过forcedomain中的环境变量设置端口时重定向循环(node.js,express)

javascript - 范围错误 : Maximum call stack size exceeded in node_modules -> elasticsearch

node.js - 构建时出现 Nativescript 错误

javascript - 发送错误后无法设置 header 。我没有调用 render()/json() 两次

javascript - 分配对象索引以在对象内部可用

javascript - 在 TinyMCE 中追加属性值

node.js - 使用多个 Docker 容器 VS 标准 Node 集群时的性能和可靠性

javascript - 是什么让 Express-Session 决定开始新的 session ?

javascript - jquery - css 在 .after() 之后不起作用