gpt4 book ai didi

node.js - 如何编写 Express 路由器来排除路径

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:10 25 4
gpt4 key购买 nike

我有一个网站,我正在编写一个在每个页面上运行的页面顶部例程:

app.all("*",function(req,res,next){
https.get("this.site.com/api", do_stuff);
next();
}

然后我意识到该函数的一部分会在我自己的网站上点击/api,这意味着当它这样做时,它将尝试无限地调用自身。

只有/api 下的页面需要排除,因此编写一条执行尽可能少操作的路由是最有意义的。

我还在某个地方看到了一个看起来可以使用真正的正则表达式的示例,但我也无法使其工作。

我试过了...

app.all("!(/api*)*", ...

app.all(/!(\/api.*).*/

...但那些似乎没有让任何东西通过。我在文档中找不到排除项,这是 Express 可以处理的吗?如果是这样,怎么办?

最佳答案

您可以将编程逻辑放入中间件中:

app.all("*",function(req,res,next){
if (req.originalUrl.startsWith('/api')) {
// skip any /api routes
next();
} else {
https.get("this.site.com/api", do_stuff);
next();
}
}
<小时/>

更简洁的整体设计是在此中间件之前插入一个 /api 路由器,并确保它处理自己的 404 错误(因此它永远不允许路由继续到其他路由处理程序)。

app.use('/api', apiRouter);

// no /api routes will get here
app.all("*",function(req,res,next){
https.get("this.site.com/api", do_stuff);
next();
}

关于node.js - 如何编写 Express 路由器来排除路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48836148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com