paint-brush
AngularJS ng-routing links without hash bang on Appengine with Pythonby@igor_98383
1,414 reads
1,414 reads

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

by Igor RendulicJune 9th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

This weekend I started working on a simple Web Page and decided to use Googles <a href="https://cloud.google.com/appengine/docs/standard/python/quickstart" target="_blank">Appengine Standard Environment</a>.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - AngularJS ng-routing links without hash bang on Appengine with Python
Igor Rendulic HackerNoon profile picture

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.