Hackernoon logoAngularJS ng-routing links without hash bang on Appengine with Python by@igor_98383

AngularJS ng-routing links without hash bang on Appengine with Python

Author profile picture

@igor_98383Igor Rendulic

This weekend I started working on a simple Web Page and decided to use Googles Appengine Standard Environment.

It’s smooth sailing until you wan’t to make your website links looking pretty. By pretty I mean removing the nasty hash signs when navigating the pages. Based on $location AngularJS Docs there are two configuration options:

  1. Hashbang mode
  2. Html5 mode (only modern browsers support it)

Obviously we need Html5 mode to remove the hashes. AngularJS describes Html5 mode:

In HTML5 mode, the $location service getters and setters interact with the browser URL address through the HTML5 history API. This allows for use of regular URL path and search segments, instead of their hashbang equivalents.

Setting up Html5 Mode is easy. First we need to add $locationProvider to Angular app config:

var App = angular.module(‘App’, [‘ngRoute’]); App.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode({ enabled: true });

Then we need to add base href in index.html and we’re done.

<head> <meta charset=”utf-8"> <base href=”/”></head>

The Problem

The problem is when refreshing a subpage directly(e.g. /about). To solve this we simply need to make a “url rewrite” as stated in AngularJS docs. On server such as Apache you could use .htaccess file for instance but since we’re working on Appengine we don’t have access to the server.

The solution

We need to tell webapp2 to map all urls to index.html.

class RefreshPageHandler(webapp2.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'app/index.html')
self.response.out.write(template.render(path, {}))
APP = webapp2.WSGIApplication([
('/about', RefreshPageHandler),
('/contact', RefreshPageHandler),
('/', RefreshPageHandler),
], debug=True)

You can find an a project example on GitHub

The same solution works on any application server. See this link for Java Servlets for example.


The Noonification banner

Subscribe to get your daily round-up of top tech stories!