2013-07-03 84 views
0

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

我可以做这样的事情:

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

然而,这会导致页面的URL来改变和一个单独的HTTP请求assumedly制成。

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

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

但是这是非常愚蠢的我的原因很明显。

+0

这是可能的吗?我想我可以发回一段数据(可能在查询字符串中)被应用程序用来更新网址 –

回答

0

最后,我用这个中间件服务于应用程序的页面时适当

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

0

如果你仍然在努力完成这项工作,我可能会找到一个出发点。 Alexander Beletsky拥有Backbone.js + Express SPA样板库。Located Here

有关它是如何出现的简短文章,您可以阅读他的文章Dzone

+2

请注意,[仅限链接回答](http://meta.stackoverflow.com/tags/link-only-answers/info),所以SO答案应该是搜索解决方案的终点(而另一个引用的中途停留时间往往会随着时间的推移而变得过时)。请考虑在此添加独立的摘要,并将链接保留为参考。 – kleopatra

相关问题