2

I have somes difficulties to understand the behavior of Angular.js routing

Here is my code

my app.js:

'use strict';

var app = angular.module('myApp', []).
  config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider.when('/game/room', {templateUrl: 'roomGame', controller: roomCtrl});
    $routeProvider.otherwise({redirectTo: '/game/room'});
    $locationProvider.html5Mode(true);
  }]);

index.js where I define the routes server side:

app.get('/game', function (req, res)
{
  console.log("we are in /game");
  res.render("game/index", {
      user: req.session
  });
});
app.get('/game/roomGame', function (req, res)
{
  console.log("we are in /game/roomGame");
  res.render("game/roomGame";
});

index.jade:

div(ng-controller="indexCtrl")
    a(href='/') Quitter

    div(ng-view)

And there is an other file: roomGame.jade but it's not important to show you the source code.

Now I open my browser and enter : localhost:3000/game.

As expected I'm redirected to localhost:3000/game/room and it shows me the expected view.

But when I enter : localhost:3000/game/room or localhost:3000/game/foo it shows me "cannot GET /game/xxx"

I want to be redirected to /game and then to /game/room. How it is possible ?

1 Answer 1

1

When you see the expected view, are you being redirected to http://localhost:3000/#/game/room? Note the #.

When you enter http://localhost:3000/game/room, this hits the express server, and not your Angular app, trying to match /game/room, hence the message you're seeing.

One idea is to go like this on your server:

app.get('/game/:what', function (req, res) {
    res.redirect('/#/game/' + req.params.what);
});

or more likely:

app.get('/game/*', function (req, res) {
    res.redirect('/#/game');
});

This will redirect things from express to a place where Angular can deal with them.

Sign up to request clarification or add additional context in comments.

1 Comment

No, I see localhost:3000/game/room (without #) But if I delete "$locationProvider.html5Mode(true);" from app.js and apply somes changes on app.js. I see "localhost:3000/Jeu1#/room".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.