Node + Express与静态HTML。如何将所有请求路由到index.html? [英] Node + Express with static HTML. How to route all requests to index.html?
问题描述
我正在使用Node + Express的单页面网页应用程序,还可以使用handelbars进行平板化。目前,一个index.html从一个漂亮的标准server.js文件提供的一切都很好:
I am working on a single page web app using Node + Express and handelbars for tempalting. Everything currently works well from a index.html which served from a pretty standard server.js file:
var express = require('express');
var server = express();
server.use(express.static(__dirname + '/public'));
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
从 http:// localhost:10001 / / code>。我的问题是我在应用程序中使用推送状态,因此浏览器可能会显示一个URL,如
http:// localhost:10001 / foo / bar
,然后如果我刷新页面,我收到错误无法GET / foo / bar
,因为没有路由。
This works perfectly when loading from http://localhost:10001/
. My issue is that I'm using push states in the app, so the browser may show a URL like http://localhost:10001/foo/bar
and then if I refresh the page, I get the error Cannot GET /foo/bar
since there is no route for this.
所以我的问题,赦免我难以置信的noobishness,当谈到节点,我可以让所有请求路由到index.html?我的应用程序中的JavaScript可以处理在页面加载时基于URL参数显示正确的内容。我不想定义自定义路由,因为数字会很大,并且它们的路径可以动态地更改。
So my question, and pardon my incredible noobishness when it comes to node, can I make it so all requests route to index.html? The JavaScript in my app can handle showing the right content based on URL params on page load. I don't want to define custom routes as the number would be large, and the paths for them can change dynamically.
推荐答案
var express = require('express');
var server = express();
server.use('/public', express.static(__dirname + '/public'));
server.get('/*', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var port = 8000;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
这篇关于Node + Express与静态HTML。如何将所有请求路由到index.html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!