Nodejs路径中间件不适用于特定模式

时间:2019-03-20 02:32:01

标签: node.js express path

我正在使用中间件来更正没有尾随正斜杠的url请求。如果路径的最后一个字符不是/或路径为/js//stylesheets//images/sitemap.xml,则不要附加/到路径的尽头。这在大多数情况下都有效,但是由于某种原因,路径返回的是我拥有的图像的/images/footer-logo.png/,但是没有/images/header_logo.svg的正斜杠。这让我很困惑,因为它们都包含相同的目录,但是一个目录正确显示,而另一个目录却不正确。推动这种行为的中间件可能出了什么问题? /images/ ===等于0的原因是,console.log显示此路径不同于其他具有-1的路径。不知道为什么会这样。

中间件:

//Add trailing slash to url
router.use(function(req, res, next) {
    //Check for GET or HEAD request
    var method = req.method.toLowerCase();

    console.log(req.path)
    console.log(req.path.indexOf('/images/'))
    //If request is GET | HEAD and last path value is not '/' and path length is greater than 1 and path does not match js | css | images
    if (['get', 'head'].includes(method) && req.path.substr(-1) != '/' && req.path.length > 1 && req.path.indexOf('/js/') === -1 && req.path.indexOf('/stylesheets/') === -1 && req.path.indexOf('/images/') === 0 && req.path.indexOf('/sitemap.xml') === -1) {
        console.log("modify path")
        console.log(req.path)
        var query = req.url.slice(req.path.length);
        res.redirect(301, req.path + '/' + query);
    } else {
        next();
    }
});

.png示例代码:

<!-- Logo -->
    <a class="d-inline-flex align-items-center mb-3" href="/">
        <img src="/images/footer-logo.png" alt="Footer Logo">
    </a>
    <!-- End Logo -->

0 个答案:

没有答案