繁体   English   中英

如何在Express for Node中重定向到单页Web应用程序

[英]How to Redirect to Single Page Web App in Express for Node

我正在编写一个带有单页Web应用程序的网站(该网站的其余部分只是提供的静态文件)。 我正在尝试编写一个用于Express的中间件,以将所有遵循模式'example.com/app'的请求重定向到'example.com/app',以便请求诸如'example.com/app/my/specific/ page /'将导致同一页面被发送。 这个问题的关键问题是浏览器地址栏中的url不能更改,以便javascript应用程序本身可以解释它并显示正确的内容。

我本可以这样做的:

app.use( '/app', function ( req, res ) {
    res.redirect('/app');
});

但是,这会导致页面的URL更改,并且假定会发出单独的HTTP请求。

最明显的替代解决方案是做这样的事情:

app.use( '/app', function ( req, res ) {
    res.sendfile(__dirname + '/public/app/index.html');
});

这里的问题是,像'example.com/app/my/specific/page/'这样的请求后,页面中的资源会显示在错误的位置。 例如,如果我在页面上有图像,那么它将查找example.com/app/my/specific/page/image.jpg。 由于没有返回图像,因此不会在页面上显示。 所有外部脚本或样式表都会发生这种情况。

我也尝试过这样的事情:

app.use( '/app', function ( req, res ) {
    res.sendfile(__dirname + '/public/beta' + url.parse(req.url).pathname);
});

但由于显而易见的原因,这对我来说非常愚蠢。

最后,我使用此中间件在适当的时候提供应用程序的页面

// all unmatched requests to this path, with no file extension, redirect to the dash page
app.use('/dash', function ( req, res, next ) {
    // uri has a forward slash followed any number of any characters except full stops (up until the end of the string)
    if (/\/[^.]*$/.test(req.url)) {
        res.sendfile(__dirname + '/public/dash/index.html');
    } else {
        next();
    }
});

然后我设置使​​用base HTML元素,其中href属性指向根。

如果你还在努力实现这个目标,我可能已经找到了一个起点。 亚历山大Beletsky有Backbone.js的+快递SPA样板回购设在这里

有关它是如何形成的简短文章,您可以阅读他关于Dzone的文章。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM