快速中间件访问req.params [英] Express middleware access to req.params

查看:84
本文介绍了快速中间件访问req.params的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想隔离一段代码,该代码将检查req.paramsreq.body的每个请求所需的值.我发现的是,如果我尝试在app.use(app.router)之前访问那些值,那么该请求就没有被解析为包括那些对象.如果我尝试在 app.use(app.router)之后插入中间件,则它们会一起被跳过.

I'd like to isolate a piece of code that would inspect either req.params or req.body for a value that is required on every request. What I'm finding is that if I try to access those values before app.use(app.router) then the request hasn't been parsed to include those objects. If I try to insert the middleware after app.use(app.router) then it gets skipped all together.

我该怎么做才能在一处处理这些值,以便准备好供下游路线和模型使用?

What can I do to work on these values in one place so that the work is ready to be used by downstream routes and models?

推荐答案

只需在每个路由中内联运行中间件,

Just run the middleware inline with each route,

const middleware = (req, res, next) => {
    console.log(req.params.id);
    next();
};

app.get('/test/:id', middleware, (req, res) => {
    res.send('hi');
});

这篇关于快速中间件访问req.params的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆