在express.js中使用路由服务静态文件

Serve static files using routes in express.js

本文关键字:路由 服务 静态 文件 express js      更新时间:2023-09-26

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

当路由为example.com/about它应该提供大约。html

我对提供静态文件所做的研究似乎表明,这不是完全可能的。是这样吗,还是我漏掉了什么?

你需要使用路由器

来提供你的静态文件
app.get('/about', function(req, res) {
    res.render('about.html');
});
在此之前,您应该为html呈现引擎设置一个中间件

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

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

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

// 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();
});

如果您有很多静态页面,理想的方法是将它们放在单个路由中,我们称之为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')());和你很好去。

试试这个

app.use(express.static(path.join(__dirname, 'xyz')));

其中xyz是您试图使其作为静态可用的文件夹。文件夹名称相对于应用程序根目录