stateProvider使用htm5Mode无法GET错误

时间:2015-12-07 15:08:19

标签: angularjs connect-modrewrite

我正在使用stateProvider和$ locationProvider.html5Mode:

    // Redirect any unmatched url
    $urlRouterProvider.otherwise("/cool");  

    $stateProvider
        // Dashboard
        .state('cool', {
            url: "/cool",
            templateUrl: "views/cool.html"
        });

     $locationProvider.html5Mode(true);

但是当我http://localhost:8080/cool时,我会收到 Cannot GET /cool 错误。 http://localhost:8080/http://localhost:8080/#/cool工作正常。

经过一番研究后我发现问题是因为咕噜声连接。所以我添加了modRoute来将所有网址路由到index.html:

livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              modRewrite([
                '!\\.\\w+$ /'
              ]),

但现在问题是每个网址都是http://localhost:8080/uncoolhttp://localhost:8080/cool

2 个答案:

答案 0 :(得分:0)

首先,确保你的头上有“基础”标签。

<base href="/">

然后确保您的“/ cool”页面与“/”相同。如果没有,服务器将发回404(如预期的那样)。所有“子页面”都必须如此。

要测试是否是这种情况 - 创建一个href为“/ cool”的链接,angular应该使用pushState“内部”处理,这与“浏览”到该页面不同。这意味着,当您单击该链接时,该页面将按预期运行,但如果您重新加载( CTRL + R ),您将收到错误。

答案 1 :(得分:0)

如果您使用html5mode,则必须在文档的<base>部分中加入head标记。您可以将requireBase设置为false,并使用html5mode而不使用<base>标记。请查看angular documentationui-router documentation