【问题标题】:How to correct set root route in Rails 4 for AngularJS?如何在 Rails 4 中为 AngularJS 更正设置根路由?
【发布时间】:2014-04-19 02:17:59
【问题描述】:

我在将 Rails 路由与 AngularJS 集成时遇到了麻烦。

当我在浏览器输入中转到“localhost:3000”时,它会将我重定向到“localhost:3000/#/auth/sign_in”

但“sign_in”模板未呈现。

然后,如果我转到“localhost:3000/#/”,它会将我重定向到“localhost:3000/#/auth/sign_in”并正确呈现“sign_in”模板。

如何解决它,当我转到“localhost:3000”然后渲染“sign_in”时?

此处的路由器代码:http://pastie.org/8917505

谢谢!

【问题讨论】:

    标签: ruby-on-rails angularjs routing


    【解决方案1】:

    我找到了解决办法。

    您需要为 AngularJS 启用 HTML5 模式

    angular.module('app').config(['$routeProvider', '$locationProvider',
      function ($routeProvider, $locationProvider) { 
      ...
        $locationProvider.html5Mode(true);
      }]
    )
    

    您还需要添加<base> html标签:

    <html>
      <head>
        <base href="/">
          ...
      </head>
    </html>
    

    当您再次在浏览器 URL 输入中按 Enter 时,它修复了 Angular 对 URL-path 的错误处理。没有这个,最后一个“域”将被重复:

    localhost:3000/auth/sign_in

    localhost:3000/auth/auth/sign_in

    ...

    您还需要在服务器端(在 Rails 中)为所有 SPA 路由编写正确的路由:

    config/routes.rb

      root 'application#main'
    
      get '*path', to: 'application#main'
    

    【讨论】:

    • 这个在 IE9 中测试过吗?我期望的是他们重定向到域的根目录并在之后处理所有内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    相关资源
    最近更新 更多