为所有以/api开头的路由运行Express中间件? [英] Run express middleware for all routes except that are starting with /api?
问题描述
我有一个Express中间件,可以像这样在所有其他路由之后将React呈现在服务器上:
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 }));
});
});
由于未指定任何路由,因此该中间件将对所有请求执行.我想从中排除所有/api
路线.问题是,即使我在此中间件之前创建了所有API路由,也总是有可能在/api/nonexistantendpoint
路径上执行该中间件.
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.
更确切地说,我正在寻找一个正则表达式,使该中间件对除/api
开头的任何路径之外的所有路径都执行.
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
.
谢谢!
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.
此帖子要求您有条件地检查URL在中间件中.
This post asks you to conditionally check for URL inside the middleware.
推荐答案
尝试一下:
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 }));
});
});
这篇关于为所有以/api开头的路由运行Express中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!