Regular expression in express route handler overriding default route

var express = require('express');
var tracker = require('../lib/pixel-track')
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'index' });
});

router.get(/^\/(([0-9a-zA-Z\._-])+.(gif|GIF))$/, tracker.requestHandler);

module.exports = router;

      

So I have this express router. According to my logic, this second operator matches any request for `/whatever.gif, and the first one only matches /. For some reason, requests for / are still sending gif. I'm a little confused as to how the regex route handler took the route pointer handler.

Interestingly, I have the same route and tracker code in the location / api and it works fine and does not override the index. Also, if I comment out router.get ('/' ... route it still renders a pixel to localhost: 4000

+3


source to share


1 answer


I would do it without using the Router module directly. Not sure what you are aiming for using it this way?

You also don't need such a complex regex:

var express = require('express');
var app = express();

/* GET home page. */
app.get('/', function(req, res) {
    console.log("got /");
    res.end("/");
});

app.get(/^\/[\w-.]+\.gif$/i, function(req, res) {
    console.log("got gif");
    res.end("a gif!");
});

app.listen(8000);

      

Update

Best I can tell, the reason is that it is not handling your original route in your code, because in your repo the api

var path (path to the index file) is equal var api = require('./routes/api/index');

, whereas your index is set to indexRoute

and you are not using anything. Remember that in routes, the path defined in app.use

is treated as the base path, so:



Assuming you have this in your app.js application:

var indexRoute = require('./routes/index');
var api = require('./routes/api/index');
app.use('/', indexRoute);
app.use('/api', api);

      

And these route handlers:

// /routes/api/index.js
router.get('/', function(req, res) {
    res.send('You called api route /');
});

// /routes/index.js
router.get('/', function(req, res) {
    res.send('You called index route /');
});
router.get(/^\/[\w-.]+\.gif$/i, function(req, res) {
    res.end("a gif!");
});

      

It seems to work for me ( app.use(express.static(path.join(__dirname, 'public')));

blocking the route though /

!).

+1


source







All Articles