0

How can I escape routes in Express and Node.js when using the /: notation? Here's what I'm doing:

app.get('/:route1/:route2', function(req, res){
  var route1 = req.params.route1;
  var route2 = req.params.route2;
  MongoClient.connect(MongoUrl, function(err, db) {
        if(err) throw err;
        db.collection(route1)
        .findOne({'_id' : new ObjectID(route2)},
            function(err, doc){
                res.send(doc);
            });
        });;

But by doing that, it won't load the js or css. I've tried if statements to no avail:

if(req.params.route1 !== 'javascripts'){//then do something}
R.A. Lucas
  • 1,121
  • 1
  • 12
  • 17

3 Answers3

0

Are you using the connect static middleware?

app.use(express.static(__dirname + 'public'))

This says "any request to a file in the /public folder, serve it as a static file".

Make sure this appears above any app.get routes, so it will be used first.

Michael Tang
  • 4,686
  • 5
  • 25
  • 24
  • I would recommend against using `static` before `router` because [doing so has performance implications](http://stackoverflow.com/a/12695813/201952). – josh3736 Dec 11 '13 at 03:19
0

you should move your static middleware above your route

app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);

app.get('/:route1/:route2', api.function);
Ryan Wu
  • 5,963
  • 2
  • 36
  • 47
  • 2
    I would recommend against using `static` before `router` because [doing so has performance implications](http://stackoverflow.com/a/12695813/201952). – josh3736 Dec 11 '13 at 03:17
0

First, without any knowledge of what you're doing or how your app is structured, I can't say for sure, but:

What you're doing (routes like /:var1/:var2) is a code smell to me. If api.function looks something like

if (req.params.var1 == 'foo') {
   // do stuff
} else if (req.params.var1 == 'bar') {
   // do other stuff
}

...that's not really the correct way to structure an Express application. In general, it should look more like

app.get('/foo/:var2', function(req, res) {
    // do stuff
});

app.get('/bar/:var2', function(req, res) {
    // do other stuff
});

That being said, if you really need to have your route handler ignore a certain value, you could just call next:

app.get('/:route1/:route2', function(req, res, next) {
    if (req.params.route1 == 'javascripts') next();
    else {
        // do something
    }
});
josh3736
  • 139,160
  • 33
  • 216
  • 263