2014-09-01 55 views
0

这里是我的路由器:为什么骨干不调用简单的路由[及其相应的功能]?

var MyRouter = Backbone.Router.extend({ 
    initialize: function(){ 
     Backbone.history.start({ pushState:true }); 
    }, 
    routes: { 
     'hello' : 'sayHello' 
    }, 
    sayHello: function(){ 
     alert('Saying hello'); 
    } 
}); 

注意,我用{ pushState:true }提供的网址没有哈希代码。

我还使用一个Node.js的服务器来处理路线:

var express = require('express'); 
var app = express(); 
app.use(express.static(__dirname)); 
app.listen(3010); 

当我浏览到http://localhost:3010#hello我的浏览器它更改为http://localhost:3010/hello的路线,但它工作正常。但是,当我亲自导航到http://localhost:3010/hello时,出现Cannot GET /hello错误。

这可能有一个简单的答案,但任何人都可以阐明我可能做错了什么?

在此先感谢。

+0

当你调用URL以''#它会尝试加载骨干定义的路由。但直接调用它像'http:// localhost:3010/hello'正在调用你没有定义的快速路由(即使pushstate为true,你需要用#调用你的骨干路由) – Sami 2014-09-01 07:27:40

回答

0

添加一个明确的路线来处理任何URL片段

app.use('/*', function(req, res) { 
    // send your backbone app 
    req.sendFile(__dirname + '/index.html'); 
}); 
+0

现在我得到一个TypeError:对象#没有方法'sendFile''错误。 – Wilhelm 2014-09-01 13:26:10

+1

@Wilhelm我不知道确切的API,对不起,它是'res.sendFile' http://expressjs.com/4x/api.html#res.sendFile – user3995789 2014-09-01 13:29:00

+0

那一个做到了,谢谢user3995789。 – Wilhelm 2014-09-01 15:15:29