2016-01-28 24 views
0

我正在使用Laravel 5和Angular。如何使Laravel 5重定向到沒有散列(#)的Angular路線?

默認情況下,Angular將/#/添加到URL中。

我不喜歡那/#/所以我使用Angular的$locationProvider.html5Mode(true);刪除它。

現在每當我試圖訪問一個角度URL,Laravel拒絕重定向我,相反,它會導致一個錯誤NotFoundHttpException說:

對不起,您要找的頁面無法找到。

NotFoundHttpException在RouteCollection.php線161:

這是很符合邏輯,因爲路由沒有在Laravel的路線文件中定義。

如何解決這個問題?

更多詳細信息:

  • 當我訪問http://whatever.app/#/dashboard/home一切工作正常(laravel知道這是角路線,然後角擺脫#,這樣的URL成爲http://whatever.app/dashboard/home沒有一個錯誤)。
  • 當我訪問http://whatever.app/dashboard/home Laravel顯示錯誤NotFoundHttpException

回答

4

編輯render功能在app/Exceptions/Handler.php文件:

public function render($request, Exception $e) 
{ 
    if ($e instanceof ModelNotFoundException) { 
     $e = new NotFoundHttpException($e->getMessage(), $e); 
    } 

    // handle Angular routes when accessed directly from the browser without the need of the '#' 
    if ($e instanceof NotFoundHttpException) { 

     $url = parse_url($request->url()); 

     $angular_url = $url['scheme'] . '://' . $url['host'] . '/#' . $url['path']; 

     return response()->redirectTo($angular_url); 
    } 

    return parent::render($request, $e); 
} 

現在只要您嘗試訪問http://whatever.app/dashboard/home laravel檢測路由不存在,將其轉換爲http://whatever.app/#/dashboard/home然後把它通過anguar去除是http://whatever.app/dashboard/home再次,但這次沒有錯誤:)

0

當您訪問下面的URL時,Laravel顯示錯誤NotFoundHttpException。

http://whatever.app/dashboard/home 

手段laravel沒有在routes.php文件

也許當你的命中http://whatever.app/#/dashboard/home您的角度重新導向至其他網址laravel工作正常(請參閱您的角度控制器templateUrl和url值這個這條路線路線,如果你想要的話,檢查它並從這裏管理你的laravel路線)。

但是,當你點擊url http://whatever.app/dashboard/home,它直接去laravel路線,並給出錯誤。

所以現在你想從#url中刪除#。 這些都是一些解決方案鏈接

https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag

Removing the fragment identifier from AngularJS urls (# symbol)

AngularJS routing without the hash '#'

0

在控制器使用

missingMethod(){ return $this->getIndex(); }

。這將檢查你的路線是否存在,如果它不是一些laravel路線 - 返回索引。

1

馬哈茂德扎爾特的答案是正確的。但不要考慮查詢字符串。

對於將查詢添加到URL,您需要更改URI的URL並從中獲取查詢。

// handle Angular routes when accessed directly from the browser without the need of the '#' 
if ($e instanceof NotFoundHttpException) { 

    $url = parse_url($request->getUri()); 

    $angular_url = $url['scheme'] . '://' . $url['host'] . '/#' . $url['path'] . (isset($url['query']) ? "?".$url['query'] : "") ;; 

    return response()->redirectTo($angular_url); 
} 
相關問題