How to work with Express Routing with Angular routing with HTML5 style URLs?

I would like to make an AngularJS application with HTML5-style URLs (i.e. without the # fragment in the URL). So in the routing controller module of my Angular application, I have something like the following:

 angular.module('app').config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider) { $locationProvider.html5Mode(true) ... } $routeProvider .when('/1/:param', /* do something */) .when('/2/:param', /* do something else */) .when('/3/:param', /* do something else again*/); 

A number of working examples, such as AngularFun , do not use HTML5 mode. For a request like http://localhost:3005/#/1/foo it’s clear that

  • the part http://localhost:3005/ processed by the server / using Express. Express happily serves our Angular -enabled index.html
  • the /1/foo route is handled by the Angular router client side

Let's say that our server.coffee looks like a standard, something like below (we serve the static dist directory containing our compiled, mined Angular sources:

 express = require 'express' routes = require './routes' dir = "#{__dirname}/dist" # sources live here port = process.env.PORT ? process.argv.splice(2)[0] ? 3005 app = express() app.configure -> app.use express.logger 'dev' app.use express.bodyParser() app.use express.methodOverride() app.use express.errorHandler() app.use express.static dir # serve the dist directory app.use app.router routes app, dir # extra custom routes 

If we use HTML5 mode, our URL http://localhost:3005/#/1/foo becomes http://localhost:3005/1/foo (no more hash # ). This time, the entire URL is intercepted by Express, and it gets confused because we do not define routes other than / .

What we would like to say is that the last part of the URL ( /1/foo ) must be "delegated" to Angular for processing. How can we say that?

+4
source share
1 answer

Everything seems to work. However, I did not do this work myself. I relied on this skeleton project: https://github.com/thanh-nguyen/angular-express-seed-coffee

This allows you a certain degree of control over which paths are processed by the client and which are processed by the server.

-1
source

All Articles