Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve assets before other routes

I am developing a web app using Node.js, Express and AngularJS.

I am serving my front-end JavaScript from the public folder, so e.g. that HTTP GET /lib/angular/angular.min.js would presumably return the AngularJS JavaScript.

However, as I want all requests to get handled by the Angular router in the browser, I have a catch-all route defined as follows:

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

The problem is that this route overrides the static asset routing, in which case it always run, even when a static asset is requested.

Is there a way to tell Express to process static assets before the custom routes propagate? Are there perhaps any other clever ways of avoiding this issue?

The Express configuration is as follows:

// Generated by CoffeeScript 1.7.1
(function() {
  var ExpressConfig, crypto, express, path, pkg;
  crypto = require('crypto');
  express = require('express');
  path = require('path');
  pkg = require('../package');

  ExpressConfig = (function() {
    function ExpressConfig() {}

    ExpressConfig.prototype.configure = function(ENV) {
      var APP_ROOT, app;
      APP_ROOT = path.join(__dirname, '../');
      app = express();
      app.set('port', pkg.config.port);
      app.set('views', APP_ROOT + 'webapp');
      app.set('view engine', 'jade');
      app.use(express.favicon());
      app.use(express.logger('dev'));
      app.use(express.json());
      app.use(express.urlencoded());
      app.use(express.methodOverride());
      app.use(express.cookieParser(crypto.randomBytes(20).toString('hex')));
      app.use(express.session());
      app.use(app.router);
      app.use(require('stylus').middleware(APP_ROOT + 'public'));
      app.use(express["static"](APP_ROOT + 'public'));
      if (ENV === 'development') {
        app.use(express.errorHandler());
      }
      return app;
    };
    return ExpressConfig;
  })();
  module.exports = ExpressConfig;
}).call(this);

//# sourceMappingURL=express-config.map
  • I can verify that the configuration is run before the catch-all route definition, as I have checked it by logging in each place to check the order.

  • I can also verify that the assets configuration works when the catch-all route is removed.

like image 555
whirlwin Avatar asked Nov 29 '25 21:11

whirlwin


1 Answers

The static middleware should appear before app.router and the specific route.

// first
app.use(express["static"](APP_ROOT + 'public'));

// second
app.use(app.router);

// last
app.get('/*',whatever);
like image 137
Hector Correa Avatar answered Dec 03 '25 23:12

Hector Correa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!