Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correct set root route in Rails 4 for AngularJS?

I have a troubles with integrating Rails routing with AngularJS.

When I go to "localhost:3000" in browser input, it redirect me to the "localhost:3000/#/auth/sign_in"

but 'sign_in' template not render.

Then, secondary if I go to the "localhost:3000/#/", it redirect me to the "localhost:3000/#/auth/sign_in" and render 'sign_in' template right.

How to fix it, when I go to "localhost:3000" then render 'sign_in' ?

Router code here: http://pastie.org/8917505

Thanks!

like image 291
Oleksandr Bratashov Avatar asked Jan 12 '23 00:01

Oleksandr Bratashov


1 Answers

I have found the solution.

You need to enable HTML5 mode for AngularJS:

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

You also need to add the <base> html tag:

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

It fixes Angular's incorrect processing of URL-path when you press Enter in the browser URL input again. Without this, the last 'domain' will be repeated:

localhost:3000/auth/sign_in

localhost:3000/auth/auth/sign_in

...

You also need to write correct route on server side (in Rails) for all SPA routes:

config/routes.rb

  root 'application#main'

  get '*path', to: 'application#main'
like image 187
Oleksandr Bratashov Avatar answered Jan 18 '23 14:01

Oleksandr Bratashov