简体   繁体   中英

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. 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...

The function I'm referring to is 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 .

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() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM