1

I have a very simple Express router and I'm trying to intercept a wildcard route that ends with !. It looks like this:

module.exports = function (args) {
    return args.express.Router()
        .get(/^\/(.*)!$/, function (req, res) {
            res.json('Ends with a bang! ' + req.baseUrl);
        })
        .get('/*', function (req, res) {
            res.json('Normal path: ' + req.baseUrl);
        })
};

When I request http://localhost:3000/test/abcd! I always get this response: "Normal path: /test/abcd!", but I was expecting the Ends with a bang! response. Regex isn't my strong suit, but it seems so simple... what am I doing wrong?

Thanks for your help, SO community, as always.

M Miller
  • 5,364
  • 9
  • 43
  • 65
  • 1
    Is an exclamation mark even allowed in that part of the URL ? – adeneo Jan 31 '15 at 17:44
  • I think so... http://stackoverflow.com/questions/1547899/which-characters-make-a-url-invalid – M Miller Jan 31 '15 at 17:47
  • Did you try escaping it `/^\/(.*)\!$` – adeneo Jan 31 '15 at 17:47
  • I did. My IDE gives me an underline which makes me think `!` isn't significant and it still isn't matching for me... – M Miller Jan 31 '15 at 17:49
  • Good point, they didn't specify where in the URL it was valid. Let me try a different character, like `_` – M Miller Jan 31 '15 at 17:50
  • Even `_` didn't work. For some reason my path isn't matching this regex. – M Miller Jan 31 '15 at 17:51
  • Huh... in the fallback route (`/*`), I placed this: `console.log(req.baseUrl, /^\/(.*)_$/.test(req.baseUrl));` and it printed `true`. So Express must be doing something strange with the regex. I'll check out the Express source. – M Miller Jan 31 '15 at 17:54
  • Your regex is fine, I've tried to run it with simple express application and it works. Can you try to console.log the request uri to see if the node application receives the url as you think it should? Maybe your client is translating it to some kind of special character, how did you test it? – Matan Hafuta Jan 31 '15 at 17:55
  • It works and matches just fine for me too. – mscdex Jan 31 '15 at 18:02
  • console logging `req.baseUrl` is in fact returning what I'm expecting, i.e. `/test/abcd!`, and even the regex test I posted above returns `true`. Not sure what's going on, Express is using `path-to-regex` which does a lot of things to my expression. I'm just going to consolidate it into one route for now and use an `if` block. – M Miller Jan 31 '15 at 18:23

0 Answers0