[英]Node - How To Access Req in POST Route Middleware
I'm new to Node and Express and I'm not sure how I can access req
in a middleware function in a POST route. 我是Node和Express的新手,我不知道如何在POST路由中访问中间件函数中的req
。 Do I need to pass it in as a parameter? 我需要将其作为参数传递吗? There are other middleware functions in this route that access req
but it is not being passed in. Overall, I'm guess I'm confused as to how req
works... 在这条路线中还有其他中间件功能可以访问req
但是它没有被传入。总的来说,我猜我对req
如何工作感到困惑......
The function I'm referring to is helpers.createPermissions()
我所指的函数是helpers.createPermissions()
My Route 我的路线
app.post('/oauth/authorize/decision', login.ensureLoggedIn('connect/signin'), helpers.createPermissions(req), oauth2.server.decision());
The Function 功能
exports.createPermissions = function(req) {
console.log(req);
};
The Error 错误
ReferenceError: req is not defined
Middleware will always get passed three arguments: req
, res
and next
. 中间件总是会传递三个参数: req
, res
和next
。
So your middleware should look like this: 所以你的中间件应该是这样的:
exports.createPermissions = function(req, res, next) {
console.log(req);
// TODO: make sure you eventually call either `next` or send back a response...
};
And you can use it like this: 你可以像这样使用它:
app.post('/oauth/authorize/decision', login.ensureLoggedIn('connect/signin'), helpers.createPermissions, oauth2.server.decision());
In situations where you see middleware being called as a function, it's because you're not calling the middleware itself, but a function that's returning a middleware function. 在你看到中间件被称为函数的情况下,这是因为你不是在调用中间件本身,而是一个返回中间件函数的函数。 For example: 例如:
var myMiddlewareWrapper = function() {
// return the actual middleware handler:
return function(req, res, next) {
...
};
};
app.get('/', myMiddlewareWrapper(), ...);
This is usually done to pass extra options to the middleware handler (like with login.ensureLoggedIn()
). 通常这样做是为了向中间件处理程序传递额外的选项(比如login.ensureLoggedIn()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.