使用Node处理具有嵌套骨干目录的PushState重定向

时间:2013-12-01 00:55:52

标签: node.js .htaccess backbone.js express

我对如何处理Backbone哈希和pushState感到有点困惑。

基本上我想要

localhost:3004/#/explore

localhost:3004/explore

localhost:3004/#/profile/123456

localhost:3004/profile/123456

首先是指定我的所有静态目录,这似乎有效,因为我可以直接通过浏览器访问所有文件。

app.configure(function(){


    app.use("/js", express.static( path.join(__dirname, 'www/js')));
    app.use("/assets", express.static( path.join(__dirname, 'www/assets')));
    app.use("/style", express.static( path.join(__dirname, 'www/style')));
    app.use("/templates", express.static( path.join(__dirname, 'www/templates')));
    app.use("/config", express.static( path.join(__dirname, 'www/config')));

    app.use(express.favicon());
    app.use(express.logger());
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.session({
        secret: 'adasdasdasdasdasdasdasdasdasdasd'
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(express.methodOverride());
    app.use(allowCrossDomain);
    app.use(app.router);
    app.use(express.static(clientDir));

});

这似乎有效,因为我现在可以从位置栏导航到任何文件。

我也设置为使用pushState

Backbone.history.start({pushState: true});

我感到困惑的是捕获初始页面调用并确保它命中index.html。但是它也需要传入目录,以便BackBones路由器知道去哪里。

一些不成功的尝试包括:

app.get("*", function(req, res) {
    fs.createReadStream(path.join(clientDir, 'index.html')).pipe(res);
});

另一个

 app.get("*", function(req, res) {
    res.redirect('http://localhost:3004#/'+req.url);
});

另一个

app.get('/', function(req, res){
    res.sendfile(path.join(clientDir, 'index.html'));
});

任何想法都会有所帮助。

我对其他方法(例如htaccess等)持开放态度,但不确定如何使用heroku部署。

1 个答案:

答案 0 :(得分:2)

看起来这对我有用。

app.get('/*', function(req, res){
   res.sendfile(path.join(clientDir, 'index.html'));
});
相关问题