2014-09-01 31 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