简体   繁体   English

异常调用以表达get方法。 应该错了,但是运行良好

[英]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. Express的get方法只记录了两种调用,但是在passportjs.org的文档中显示为第三种调用。

I am learning to implement SSO using google's Oauth 2.0 strategy. 我正在学习使用Google的Oauth 2.0策略实施SSO。 During this I came across an unusual usage of app.get method. 在此期间,我遇到了app.get方法的异常用法。 Such a function call is not defined in express' documentation. Express的文档中未定义此类函数调用。

I referred to the following two pages, to ensure I wasn't mistaken: 我参考了以下两页,以确保我没有记错:

  1. Express JS documentation for app.get method Express JS文档app.get方法
  2. Passport JS documentation for app.get method 适用于app.get方法的Passport JS文档

Express js documentation has only two kinds of calls: Express js文档只有两种调用:

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: 现在,passwordjs.org中的调用似乎使用的是第二种形式,但是请注意,第二个参数(passport.authenticate)实际上是函数调用,而不是函数定义(即回调),因为它应该按照上面的#2进行:

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. 我预计会出现运行时错误,因为对app.get的调用与任何已记录的函数调用类型都不匹配。 However, the function call runs well and completes the intended task. 但是,函数调用运行良好,可以完成预期的任务。 How? 怎么样?

From Passport npm page Passport npm页面

Passport is Express-compatible authentication middleware for Node.js Passport是Node.js的Express兼容身份验证中间件

The way this works is passport exposes methods which is compatible with callback that express expects. 这是passport工作方式,它公开了与表达期望的callback兼容的方法。

The simplest callback signature which express expects is: 表达期望的最简单的callback签名是:

(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 * Express文档还在上面的链接中的可配置中间件下说明了类似的中间件功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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