如何使用页面.js和 Apache 路由/提供静态文件

How can I route to / serve static files with page.js and Apache?

本文关键字:静态 文件 路由 Apache 何使用 js      更新时间:2023-09-26

我有一个路由器设置了page.js,它路由索引页(在'/'(,项目页面(在'/projects/<projectId>/'(和静态(图像(文件。基本上,它看起来像这样:

JavaScript

init: function () {
    page.base('/');
    // IndexPage
    page('', function (context, next) {
        displayIndexPage();
    });
    // ProjectPage
    page('projects/:project', function (context, next) {
        displayProjectPage();
    });
    // image files
    page(/^.+'.(jpg|png|gif|bmp)$/, function (context, next) {
        window.location = '/' + context.path;
    });
    // Exit the middleware
    page();
}

在我的/projects/文件夹中,我有一个包含以下内容的.htaccess文件:

砰砰��

    Options +FollowSymLinks
    RewriteEngine On
    # html5 pushstate (history) support
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !index
    RewriteRule ^.*$ ../index.html [QSA,L,NE]

路由通常工作正常。当我导航到静态图像文件时,.htaccess将我放在单页应用之外,静态文件将显示在屏幕上。但是,当我在浏览器中导航回时,我不会重新进入我的应用程序;URL 更改,但没有导航,图像文件保留在屏幕上。再多的弹出或推送状态都不会让我回到我的应用程序中。

我不完全确定我在这里问了正确的问题;不确定这是关于提供静态文件,就像它是关于路由单页应用程序一样......我会对任何允许页面.js重新拾起popState的答案感到满意。

编辑:我正在从我的RewriteRule中免除文件,因为我需要在应用程序呈现的页面中提供它们。但是,当访问者单击渲染页面中的图像时,我希望浏览器仅显示该图像,而不添加标记。

如果我了解您想要的最终结果是什么,则可以使用包含覆盖整个窗口的图像的简单叠加来完成。然后捕获弹出状态事件并删除覆盖。JQuery 不是必需的,只是为了简洁。

jsfiddle 注意:您的浏览器 URL 不会更改,因为小提琴位于 iframe 内。

编辑:Stackoverflow将原点设置为null,因此请检查jsfiddle的工作示例。

var url = 'http://indianapublicmedia.org/stateimpact/files/2013/01/apple-image-300x300.jpg';
$('.image').click(function () {
    $('body').append('<div id="overlay"><img src="' + url + '"></div>').appendTo('body');
    history.pushState(null, null, 'http://stackoverflow.com/imageURL');
});
window.onpopstate = function(){
    $('#overlay').remove();
};
#overlay {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
    position: fixed;
    background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>Some content here
    <img src="http://indianapublicmedia.org/stateimpact/files/2013/01/apple-image-300x300.jpg" class='image'>
</body>

点击图片链接时,您的期望是什么?

路由图像时,不要更改位置,而是尝试对图像执行其他操作。通过 AJAX 加载它,并根据您的期望将其附加到某个元素。

// image files
page(/^.+'.(jpg|png|gif|bmp)$/, function (context, next) {
    // Culprit
    // window.location = '/' + context.path;
    showImage('/' + context.path);
});

编辑

使用非页面.js链接的图像,以允许浏览器直接处理它。例。

由于服务器端路由,jsfiddle 链接不能很好地工作,但如果您复制回服务器,它将起作用。