0

So I needed to change my URL so that google analytics could track it. Google analytics wouldn't accept it with the "/#/" (hash) in the link. That said, I used Angular's locationProvider and revised my app routing with:

(function() {
  'use strict';

  angular
    .module('mbapp')
    .config(routerConfig);

  /** @ngInject */
  function routerConfig($stateProvider, $urlRouterProvider, $locationProvider) {
    $stateProvider
      .state('home', {
        url: '/',
        templateUrl: 'app/main/main.html',
        controller: 'MainController',
        controllerAs: 'main'
      });

    $stateProvider
      .state('steps', {
        url: '/steps',
        templateUrl: 'app/steps/steps.html',
        controller: 'StepsController',
        controllerAs: 'steps'
      });      

    // use the HTML5 History API
    $locationProvider.html5Mode(true);      

    $urlRouterProvider.otherwise('/');
  }

})();

My URL is fine and changes it to http://website.com/steps rather than http://website.com/#/steps. However, now, if a user refreshes (f5) the link it then throw a 404 error and not sure why. Additionally, it seems that somehow this gets injected as the URL when the refresh is called "http://website/steps#/steps".

Any ideas on this?

Thanks much.

Mark
  • 1,812
  • 3
  • 29
  • 51
  • I had The same issue to solve it i updated the analytics onpagechange like the sugestion in this http://stackoverflow.com/questions/12989106/handle-urls-with-hash-with-google-analytics – Asaf Hananel Oct 02 '16 at 23:25
  • several angular analytics modules around...have not had this problem myself with hash based routing and have also monitored ga traffic in real time – charlietfl Oct 03 '16 at 02:52
  • @AsafHananel - do you mean the "_trackPageview"? – Mark Oct 03 '16 at 04:06

1 Answers1

0

The problem is probably on the server side. You have to configure your server so it responds to every request with your html file. For example in express:

var app = require('express')();

app.configure(function(){
  // static - all our js, css, images, etc go into the assets path
  app.use('/assets', express.static('/assets'));

  app.get('/api/users/:id', function(req, res){
    // return data for user....
  });

  // This route deals enables HTML5Mode by forwarding missing files to the index.html
  app.all('/*', function(req, res) {
    res.sendfile('index.html');
  });
});

When you reload the page, the request goes to the server side of your application, and it tries to resolve the url but it probably can't, because those routes only exists on the client side of your application.

Also it is a good idea to prefix every server side route with an /api route prefix, so you can easily distinguish between client side and server side routes.

nagyf
  • 859
  • 5
  • 17