Gopard
Gopard

Reputation: 1060

AngularJS routing Server side support (NodeJS+express)

I am using NodeJS + expressJS on server and AngularJS on client

AngularJS controller have the following routes:

app.config(function($routeProvider,$locationProvider) {
$routeProvider
 .when('/field1/:id', {
  controller: 'ctrl1',
  templateUrl: "/view/mainpages/field1.html"
})
 .when('/field2/:id', {
  controller: 'ctrl2',
  templateUrl: "/view/mainpages/field2.html"
})
........... many many 
.when('/', {
  controller: 'ctrl0',
  templateUrl: "/view/mainpages/index.html"
})
.otherwise({redirectTo : '/'});

NodeJS static:

app.all('/*', express.static(__dirname + '/client'));

How to make the server redirects all the static pages on their paths relative to the root, in the case when the call goes directly through this link.

example: server:3000/field1/23 must call server:3000/client/index.html and index must upload JS like server:3000/js/cntr1.js

Upd: I found a solution to the problem. But it looks ugly as a crutch

app.get('/field1/([0-9]+$)', function(req, res, next) { 
    req.url='/index.html';
    next();
 });
app.use('/field1', express.static(__dirname + '/client'));

Perhaps there is a more elegant solution?

Upvotes: 1

Views: 875

Answers (1)

arkoak
arkoak

Reputation: 2497

In expressjs, you can define the route using regular expression pattern matching. That means, anything under a specific set will always return the same page from the server side, and you will let angular decide what exactly to display or do which action.

Its not a great idea to redirect everything at / to same page as you need to manage your assets and they exist on the / part too , instead its a good idea to use a subdir which is easy to manage

Following snippet will redirect everything under the app path to the same page on server side

app.get('/app/*', function(req, res) {
  res.send('app_index');
})

if you do not want to be limited to one app dir, instead you have a number of different root level dirs, all of which need to point to the same page, you can do something like this

app.get('/(app|server|client|form|dashboard)/*', function(req, res) {
  res.send('app_index');
})

Upvotes: 1

Related Questions