Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run express middleware for all routes except that are starting with /api?

I have an Express middleware that renders React on the server like so, placed at the end, after all other routes:

app.use(function(req, res) {
  Router.run(routes, req.path, function(Handler) {
    var markup = React.renderToString(<Handler />);
    res.send(swig.renderFile('views/index.html', { html: markup }));
  });
});

Since no route is specified this middleware will execute for all requests. I would like to exclude all /api routes from it. The problem is even if I create all API routes before this middleware, there is always a possibility for this middleware to be executed on /api/nonexistantendpoint path.

To be more precise, I am looking for a regex that would make this middleware execute for all paths except any path starting with /api.

Thanks!


I have already looked at this SO post but couldn't find anything useful to me.

And this post contains a lot of workarounds which is also not what I am looking for.

This post asks you to conditionally check for URL inside the middleware.

like image 615
Sahat Yalkabov Avatar asked Jul 01 '15 02:07

Sahat Yalkabov


2 Answers

Try this:

app.use(/^\/(?!api).*/, function(req, res) {
  Router.run(routes, req.path, function(Handler) {
    var markup = React.renderToString(<Handler />);
    res.send(swig.renderFile('views/index.html', { html: markup }));
  });
});
like image 82
hassansin Avatar answered Nov 16 '22 01:11

hassansin


This is how I handle non existent api routes. I have api folder that contains all my api route, ideally each in their own js file and api/index.js requires all these routes like this

var router = require('express').Router();

router.use(require('./users'));
router.use(require('./it'));
//other routes.js

then at the end in my api/index.js I have this

router.use('/*', function(req, res) { //this will reject any /api/nonexistant routes
  res.send(500).end();
});

In my server js I include my api routes first

app.use('/api', require('./api'));
app.use(function(req, res) {
  console.log('dosomething');
  res.send('Hello something').end();
});
like image 29
kachhalimbu Avatar answered Nov 16 '22 00:11

kachhalimbu