【问题标题】:node.js/express: Sending static files if they existnode.js/express:发送静态文件(如果存在)
【发布时间】:2012-12-16 23:45:20
【问题描述】:

如果存在,我想从文件夹中提供 html 文件,否则回退到动态应用程序。

目前我使用类似的东西:

var express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);

server.listen(4444);

app.use("/", express.static(__dirname + '/../WebContent/index.html'));
app.use("/styles", express.static(__dirname + '/../WebContent/styles'));
app.use("/script", express.static(__dirname + '/../WebContent/script'));

//here I would like to define a rule like this:
//app.use("*.html", express.static(__dirname + '/../WebContent/*html'));

我怎样才能做到这一点?

有些教程使用了一个名为connect 的模块。如果这是解决我的问题的最优雅的解决方案,我如何将连接集成到我当前的代码中?

【问题讨论】:

    标签: node.js express socket.io


    【解决方案1】:

    您不必做任何特别的事情。

    我假设 WebContent 文件夹位于根目录中。

    如果您的所有静态内容都在同一个基本文件夹中,就像您展示的那样,您不必多次指定它。

     app.use(express.static(__dirname + '/WebContent'));
    

    如果您在 WebContent 文件夹中有一个名为 file.html 的文件,您现在可以通过 url 访问它,即 localhost:4444/file.html

    【讨论】:

    • 不,WebContent 不在根文件夹中……这就是它不起作用的原因吗?
    • @Coyote 我猜是这样。因为 __dirname 是指网络应用程序的根目录.. 所以很难说 __dirname +/../WebContent 解析到什么。
    • 谢谢!使用app.use(express.static(path.normalize(path.join(__dirname,'../WebContent')))); 完美运行!
    【解决方案2】:

    您使用了很多样板。使用routes 更容易。这是一个例子:

    var routes = require('./routes');
    
    app.configure(function () {
        ...
        app.use(express['static'](path.join(__dirname, '/../WebContent')));
        app.use(app.router);
    });
    
    // Routes
    app.get('/', routes.index);
    

    routes/index.js:

    exports.index = function (req, res) {
       res.render('index');
    };
    

    在你的项目根目录之外渲染你的 webapp 根目录是很奇怪的。感觉是不好的做法。有必要吗?

    【讨论】:

    • 这有点像拼贴画。 ../WebContent 来自另一个项目,不幸的是我也绝对需要 socket.io 来完成这个项目。
    • 路线比通常的快速使用/获取方式有什么优势?
    猜你喜欢
    • 2018-09-15
    • 2021-04-21
    • 1970-01-01
    • 2018-11-08
    • 2016-02-25
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多