dkran
dkran

Reputation: 284

Regex 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, that second statement matches any request to a ` /whatever.gif, and the first one is just for /. For some reason, requests at / still send the gif. I'm a little confused as to how the regex route handler took over my index route handler.

Interestingly I have the exact same regex route and tracker code at a /api location, and it works fine, not overriding the index. Also, if I comment out the router.get('/' ... route, it still presents the pixel at localhost:4000

Upvotes: 3

Views: 877

Answers (1)

brandonscript
brandonscript

Reputation: 72905

I'd do it without using the Router module directly. Not sure what you're aiming at with using it that way?

You also don't need such a complicated 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, reason it's not handling your original route in your code, is because in your repo, the api var (path to the index file) is var api = require('./routes/api/index'); whereas your index is set in indexRoute and you're not using that anywhere. Remember that in routes, the path defined in app.use is treated as the base-path, so:

Assuming you had this in your app.js:

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!");
});

This seems to work for me (albeit app.use(express.static(path.join(__dirname, 'public'))); was blocking the / route!).

Upvotes: 1

Related Questions