如何设置Express以使用Backbone和pushState?

时间:2012-09-05 14:50:51

标签: backbone.js routing express middleware pushstate

我正在尝试将Express设置为使用Backbone和pushState,但我不确定如何处理路由。我已经尝试添加一个中间件函数(基于https://gist.github.com/3402977)来处理任何未定义的路由,方法是将#插入到url中,但似乎中间件永远不会被调用:

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('yadda yadda'));
  app.use(express.session());
  app.use(app.router);

  // This should handle undefined routes.
  app.use(function(err, req, res, next){
    // Isn't getting called.
    newUrl = req.protocol + '://' + req.get('Host') + '/#' + req.url;
    res.redirect(newUrl);
  });

  app.use(express.static(path.join(__dirname, 'public')));
});

目前,每当我访问未在Express(http://localhost:3000/test/foo)中定义的路线时,它都会给我Could not GET /test/foo错误。我希望它重定向到http://localhost:3000/#/test/foo,以便Backbone可以处理固定链路和诸如此类的路由。我错过了什么?

1 个答案:

答案 0 :(得分:1)

对于在这里降落的后代: 答案是他的中间件应该在app.use(app.router);行之前。