[英]Are the route handlers in express called synchronously or asynchronously?
I have two redirections in a routes.js
file: 我在routes.js
文件中有两个重定向:
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. blockingController01
发送带有表单的渲染页面以输入代码。 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. 如果用户没有输入正确的代码,则如果他/她输入“ / test”或其他任何代码,则该页面应重定向到insert code
页面。
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: 所以我想知道两件事:
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. 它们按照其定义顺序被调用,因此在您的情况下,将为所有GET
请求调用blockingController01
。
That controller can pass the request along, if the token is correct, to other route handlers that match the URL. 如果令牌正确,则该控制器可以将请求传递给与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. 因此,任何GET
请求都将到达第一个路由处理程序,该处理程序将检查令牌的有效性(在这种情况下,它仅检查查询字符串参数token
的值是否为“ 12345” 。如果不是,它将呈现一个表单,但是如果令牌匹配,它将调用next()
,它将请求传递给第二个路由处理程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.