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

Node.js 如何在Express for Node中重定向到单页Web应用,node.js,express,url-routing,Node.js,Express,Url Routing,我正在用一个单页web应用程序编写一个网站(网站的其余部分只是提供的静态文件)。我正在尝试为express编写一个中间件,将所有遵循“example.com/app”模式的请求重定向到“example.com/app”,以便“example.com/app/my/specific/page/”等请求都会导致发送相同的页面。这样做的关键问题是浏览器地址栏中的url不能更改,以便javascript应用程序本身能够解释并显示正确的内容 我本可以这样做的: app.use( '/app', funct

我正在用一个单页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');
});
app.use( '/app', function ( req, res ) {
    res.sendfile(__dirname + '/public/app/index.html');
});
app.use( '/app', function ( req, res ) {
    res.sendfile(__dirname + '/public/beta' + url.parse(req.url).pathname);
});
但是,这会导致页面的url发生更改,并假定会发出单独的HTTP请求

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

app.use( '/app', function ( req, res ) {
    res.redirect('/app');
});
app.use( '/app', function ( req, res ) {
    res.sendfile(__dirname + '/public/app/index.html');
});
app.use( '/app', function ( req, res ) {
    res.sendfile(__dirname + '/public/beta' + url.parse(req.url).pathname);
});
这里的问题是,在请求“example.com/app/my/specific/page/”之后,页面中的资源将出现在错误的位置。例如,如果我在页面上有一个图像,例如,它将显示为example.com/app/my/specific/page/image.jpg。由于没有返回图像,因此它不会显示在页面上。所有外部脚本或样式表都会发生这种情况

我也试过这样的方法:

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

但出于显而易见的原因,我真是太蠢了。

如果你仍在努力实现这一目标,我可能已经找到了一个起点。Alexander Beletsky有一个Backbone.js+Express SPA样板回购


关于它是如何产生的,你可以阅读他的文章。

最后,我使用这个中间件在适当的时候为应用程序的页面提供服务

// 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
属性指向根。

这可能吗?我想我可以发回一段数据(可能在查询字符串中)供应用程序用于更新urlNote,因此答案应该是搜索解决方案的终点(而不是另一个参考的中途停留,随着时间的推移往往会过时)。请考虑在这里添加一个独立的概要,将链接作为参考。