简体   繁体   中英

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.

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

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();
});

I'm pretty sure I had the exact same use case as Sahat, here's the syntax I used for configuring two routes to handle /api matches and misses in Express.js:

// /api/* Matches
app.get( '^/api/:params*', function( req, res, next ) {
    res.send( "Matches an /api/ route." );
} );

// /api/* Misses
app.get( /^((?!\/api\/).)*$/, function( req, res, next ) {
    res.send( "NOT an /api/ route." );
} );

This assumes that all of your API routes follow a pattern of /api/* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM