简体   繁体   中英

Are the route handlers in express called synchronously or asynchronously?

I have two redirections in a routes.js file:

app.get('*', blockingController01);
app.get('/test', controller02);

The business is, that I have a 'blocking landing page' in which you have to enter a valid code to access to the rest of the site. blockingController01 sends a rendered page with a form to enter the code. If user didn't enter the a correct code then if he/she enters '/test' or any other the page should redirect to the insert code page.

I tried to solve this just putting a controller for the code page at the beginning and covering all paths with the wildcard *. So i'm wondering two things:

  1. Are the controllers that handle the same paths called asynchronously?
  2. Does express have something to avoid to call the rest of the controllers?

Thanks!

Controllers (route handlers) are not called concurrently (which is what I think you mean with "asynchronously").

They are called in order of their definition, so in your case blockingController01 will be called for all GET requests.

That controller can pass the request along, if the token is correct, to other route handlers that match the URL.

Here's a very basic example of what you're trying to do:

app.get('*', (req, res, next) => {
  if (req.query.token !== '12345') {
    // You would use `res.render()` here, this is just a quick demo:
    return res.send(`
      <form>
      Please enter a token and press enter: <input type=text name=token>
      </form>
    `);
  }
  next();
});

app.get('/test', (req, res) => {
  res.send('<h1>Correct token!</h1>');
});

So any GET request will hit the first route handler, which checks the validity of the token (in this case, it just checks if the query string parameter token has a value of "12345" . If not, it will render a form, but if the token matches it will call next() which passes the request to the second route handler.

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