简体   繁体   中英

Unusual call to express get method. Should be wrong but runs well

Express' get method has only two kinds of calls documented, however in passportjs.org's documentation it is shown being called in a third kind.

I am learning to implement SSO using google's Oauth 2.0 strategy. During this I came across an unusual usage of app.get method. Such a function call is not defined in express' documentation.

I referred to the following two pages, to ensure I wasn't mistaken:

  1. Express JS documentation for app.get method
  2. Passport JS documentation for app.get method

Express js documentation has only two kinds of calls:

1. app.get(name)
2. app.get(path, callback [, callback ...])

Now, the call in passportjs.org appears to be using the second form, but notice that second argument (passport.authenticate) is actually a function call, and not a function definition (ie callback) as it should be according to #2 above:

app.get('/auth/google',
  passport.authenticate('google', { scope: 'https://www.google.com/m8/feeds' });

I expect a run time error as the call to app.get, doesn't match any of the documented function call kinds. However, the function call runs well and completes the intended task. How?

From Passport npm page

Passport is Express-compatible authentication middleware for Node.js

The way this works is passport exposes methods which is compatible with callback that express expects.

The simplest callback signature which express expects is:

(req, res) => { /* something */ }

So any function which returns another function of the expected signature can be passed as middleware.

For example

const app = express()

function myFunc(some) {
  return (req, res) => {
    res.json(some);
  }
}

app.get('/', myFunc('something'));

*Express documentation also illustrates similar middleware function under Configurable middleware in the link above

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