如何使Laravel 5重定向到没有哈希(#)的Angular路由?

时间:2016-01-28 05:49:46

标签: angularjs laravel laravel-5 laravel-5.1 laravel-routing

我正在使用带有Angular的Laravel 5。

默认情况下,Angular将/#/添加到网址。

我不喜欢/#/,所以我使用来自Angular的$locationProvider.html5Mode(true);将其删除。

现在每当我尝试访问Angular网址时,Laravel拒绝重定向我,而是导致错误NotFoundHttpException说:

  

抱歉,找不到您要查找的页面。

     

RouteCollection.php第161行中的NotFoundHttpException:

这是非常合乎逻辑的,因为路线没有在Laravel的路线文件中定义。

如何解决这个问题?!

更多详情:

  • 当我访问http://whatever.app/#/dashboard/home时,一切正常(laravel知道它的Angular路线,然后Angular摆脱了#,因此URL变为http://whatever.app/dashboard/home而没有错误。)
  • 当我访问http://whatever.app/dashboard/home时,Laravel会显示错误NotFoundHttpException

4 个答案:

答案 0 :(得分: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,但没有错误这次:))

答案 1 :(得分:1)

Mahmoud Zalt的答案是正确的。但请不要考虑查询字符串。

要将查询包含在网址中,您需要更改URI的网址并从中获取查询。

// 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);
}

答案 2 :(得分:0)

当您访问以下网址时,Laravel会显示错误NotFoundHttpException。

http://whatever.app/dashboard/home 

表示laravel在routes.php

中没有这条路线

可能当您的点击http://whatever.app/#/dashboard/home您的角度重定向到其他网址到laravel时工作正常(请参阅此路线的角度控制器templateUrl和url值,检查此项并根据需要管理此处的laravel路线)

但是当你点击网址http://whatever.app/dashboard/home时,它会直接转到laravel路线并给出错误。

所以现在你要从网址中删除#。 这些是一些解决方案链接

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 '#'

答案 3 :(得分:0)

使用

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

在控制器中。这将检查您的路线是否存在,以及它是否不是某些laravel路线 - 返回索引。