使用express.js中的路由提供静态文件

时间:2015-06-10 03:56:49

标签: javascript express

我有一堆html文件,我想用作静态文件。但是,我需要路线中没有任何.html。

当路线是 example.com/about 它应该服务于about.html

我在提供静态文件方面所做的研究似乎表明它并非完全可能。是的,或者我错过了什么?

4 个答案:

答案 0 :(得分:1)

您需要使用路由器

提供静态文件
<img alt = "" src = File Name />

在此之前,您应该为html渲染引擎设置中间件

或者,如果你有很多静态文件,你可以使用中间件为你做这件事

https://www.npmjs.com/package/clean-urls

答案 1 :(得分:0)

您可以创建一小段中间件来处理您为其配置的任何预设名称。不在该列表中的任何内容将转到您的正常路线:

// create static file lookup table for the desired names
var staticFiles = ["about", "index", "home"].reduce(function(obj, item) {
    obj["/" + item] = true;
    return obj;
}, {});

app.use(function(req, res, next) {
    // if the path is found in the lookup table, then
    // add ".html" onto the end and get that file from the base directory
    // of you could use any source directory for those files
    if (staticFiles[req.path]) {
        res.sendFile(path.join(__dirname, req.path + ".html"));
        return;
    }
    next();
});

注意:这非常谨慎地仅提供特定文件,因此没有人可以使用其他类型的URL在您的文件系统中窥探。

以下是一个示例,其中文件从名为“html”的基目录下的子目录中提供:

app.use(function(req, res, next) {
    if (staticFiles[req.path]) {
        res.sendFile(path.join(__dirname, "html", req.path + ".html"));
        return;
    }
    next();
});

在节点v0.12 +中,您可以使用Set对象作为静态路由列表,如下所示:

var staticFiles = new Set(["/about", "/index", "/home"]);

app.use(function(req, res, next) {
    if (staticFiles.has(req.path)) {
        res.sendFile(path.join(__dirname, "html", req.path + ".html"));
        return;
    }
    next();
});

答案 2 :(得分:0)

如果您有很多静态页面,理想的方法是将它们放在一个路径中,我们称之为static.js。它可以是类似的东西,

module.exports = function () {
var router = require('express').Router();

var pages = {
    'about-us': 'path/to/about-us',
    'contact-us': 'path/to/contact-us'
};

router.get('/:page', function (req, res, next) {
    if (! pages[req.params.page]) {
        return next();
    }

    res.render(pages[req.params.page]);
});

return router;
};

将此路线附加到应用app.use(require('./static')());,您就可以了。

答案 3 :(得分:-1)

试试这个。

ArrayList: 5096
boolean[]: 1027
BitSet: 201

其中xyz是您尝试以静态方式提供的文件夹。文件夹名称相对于应用程序根目录。

相关问题