Express 单页应用程序客户端和服务器路由

Express 单页应用程序客户端和服务器路由,express,routing,single-page-application,pushstate,Express,Routing,Single Page Application,Pushstate,我有以下代码来使用HTML5 pushstate(crossroadsjs和historyjs的经典组合)处理客户端导航: 它工作得非常好。现在,为了处理url书签和共享,我添加了和express server来处理所有请求。它所做的只是重定向到index.html(一种catchall规则): 我面临的问题是,它成功地重定向到index.html,但没有在客户端加载正确的路由。因此,对www.mysite.com或www.mysite.com/anotherpage的请求将始终加载主页路由 很

我有以下代码来使用HTML5 pushstate(crossroadsjs和historyjs的经典组合)处理客户端导航:

它工作得非常好。现在,为了处理url书签和共享,我添加了和express server来处理所有请求。它所做的只是重定向到index.html(一种catchall规则):

我面临的问题是,它成功地重定向到index.html,但没有在客户端加载正确的路由。因此,对www.mysite.comwww.mysite.com/anotherpage的请求将始终加载主页路由


很明显,我缺少一些代码来拦截它并在客户端加载适当的路由。我只是不知道该怎么办。

找到了错误所在:

crossroads.parse('/')

这总是重定向到“回家”路线。我只需要稍微重构一下代码:

History.Adapter.bind(window, 'statechange', this.routeCrossRoads);

routeCrossRoads() {
    var state = History.getState();
    if (state.data.urlPath) {
        return crossroads.parse(state.data.urlPath);
    }
    else {
        if (state.hash.length > 1) {
            var fullHash = state.hash;
            var pos = fullHash.indexOf('?');

            if (pos > 0) {
                var hashPath = fullHash.slice(0, pos);
                return crossroads.parse(hashPath);
            }
            else {
                return crossroads.parse(fullHash);
            }
        }
        else {
            return crossroads.parse('/');
        }
    }
}

如果你不想麻烦的话,有一个框架将承担所有的路由维护。谢谢,但现在我正在给我的堆栈添加一个PHP框架。没什么反对的,别误会我。
var env = require('./env');
var fallback = require('express-history-api-fallback');
var express = require('express');

var app = express();
var config = env.config();
var root = __dirname + '/dist';

app.use(express.static(root));

app.use(fallback('index.html', { root: root }));

var port = process.env.PORT || 9090;

var server = app.listen(port, function () {
    console.log('Server started at: http://localhost:' + port);
    console.log(config);
});
History.Adapter.bind(window, 'statechange', this.routeCrossRoads);

routeCrossRoads() {
    var state = History.getState();
    if (state.data.urlPath) {
        return crossroads.parse(state.data.urlPath);
    }
    else {
        if (state.hash.length > 1) {
            var fullHash = state.hash;
            var pos = fullHash.indexOf('?');

            if (pos > 0) {
                var hashPath = fullHash.slice(0, pos);
                return crossroads.parse(hashPath);
            }
            else {
                return crossroads.parse(fullHash);
            }
        }
        else {
            return crossroads.parse('/');
        }
    }
}