2013-12-08 29 views
15

我有一個目錄結構的角應用在瀏覽器中直接訪問URL時,角度路由不起作用,但在單擊時可以工作?

app 
..views 
....partials 
......main.jade 
......foo.jade 
....index.jade 

和路由等定義:

「使用嚴格」;

angular.module('myApp', [ 
    'ngCookies', 
    'ngResource', 
    'ngSanitize', 
    'ngRoute', 
    'firebase', 
    'myApp.config' 
]) 
    .config(function ($routeProvider, $locationProvider) { 
    $locationProvider.html5Mode(true); 

    $routeProvider 
     .when('/', { 
     templateUrl: '/partials/main', 
     controller: 'MainCtrl' 
     }) 
     .when('/foo/:fooName', { 
     templateUrl: '/partials/foo', 
     controller: 'FooCtrl' 
     })    
     .otherwise({ 
     redirectTo: '/' 
     }); 
    }); 

我用快遞在服務器端和相關代碼:

// server.js 
    app.configure('development', function(){ 
    app.use(express.static(path.join(__dirname, '.tmp'))); 
    app.use(express.static(path.join(__dirname, 'app'))); 
    app.use(express.errorHandler()); 
    }); 

    app.configure('production', function(){ 
    app.use(express.favicon(path.join(__dirname, 'public/favicon.ico'))); 
    app.use(express.static(path.join(__dirname, 'public'))); 
    }); 

    app.get('/', routes.index); 
    app.get('/partials/:name', routes.partials); 

    //routes.js 
    exports.index = function(req, res){ 
     res.render('index'); 
    }; 


    exports.partials = function(req, res){ 
     var name = req.params.name; 
     res.render('partials/' + name); 
    }; 

的主要途徑"/"加載罰款,當我點擊"/foo/bar"局部視圖foo.jade負載預期。但是,當我嘗試直接在URL中訪問"/foo/bar"時,我從Express "cannot GET /foo/bar"得到404響應,這是有道理的,因爲沒有像express中定義的那樣的路線。但是,我認爲這是定義角度路由器的關鍵。它應該攔截這個請求,並且實際上要求"/partials/foo"。 我嘗試添加

//redirect all others to the index (HTML5 history) 
app.get('*', routes.index); 

,但它並沒有解決這個問題,似乎要趕上即使是靜態的js資產的請求,並與index.html的內容,這是非常糟糕的響應。 我確定我做錯了什麼。我如何解決這些問題以便我可以直接訪問這些網址?

回答

17

路由行爲如此的原因是html5mode打開。 注意以下行:$locationProvider.html5Mode(true);

您需要了解的是,當您嘗試直接訪問"/foo/bar"時,瀏覽器會向此URL發送HTTP GET請求。當您嘗試通過點擊鏈接訪問此網址時,就像您所說的那樣,Angular會攔截此操作並調用僅更新瀏覽器鏈接的History.pushState。

爲了使html5mode路由工作,你需要做的是實現url重寫。每個請求都必須重定向到引導AngularJS應用程序的索引文件,但這需要在服務器上完成。 Angular會自己渲染所需的頁面。

退房connect mod rewrite咕嚕的任務,做到這一點。您也可以直接聯繫this middleware

+0

但我試着在服務器上做這個: app.get('*',routes.index);那沒有用。 – algorithmicCoder

+0

我認爲你不能這樣做。如果您使用express,connect-mod-rewrite應該很容易使用。 Express寫在連接之上。 –

+0

但是,這正是在這裏完成的:https://github.com/btford/angular-express-seed/blob/master/app.js,這是標準的Angular參考。爲什麼它在這種情況下工作? – algorithmicCoder

相關問題