gpt4 book ai didi

javascript - 了解 Passport.authenticate ('local' ) 语法位

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:10 26 4
gpt4 key购买 nike

tl;dr: 我想理解代码末尾的 (req, res) 位。

我很难理解一段涉及使用本地策略的“passport.authenticate()”的代码。

我有以下(工作)路线:

router.post("/login", function (req, res, next) {
passport.authenticate('local', { session: false }, function (err, user, info) {
if (err || !user) {
return res.status(400).send({
message: "Something went wrong",
user: user
})
}

return res.send({user, info})
}) (req, res) // What´s this??
})

据我所知,该路由调用 passport.authenticate(),然后调用我在另一个文件中设置的本地策略,该策略又返回 err、user、info。执行回调后,此代码会处理可能的错误,如果一切正常,它将沿着本地策略中设置的消息发送回用户...

我不明白的是最后一点。 (req, res) 到底在做什么?我知道这是一个关键位,因为没有那条线,路由就无法工作,但我不明白为什么,也不明白它到底是什么(它是调用带有参数 req 和 res 的函数吗?它返回 req 和 res 吗?),因为我不认识该模式(它确实类似于 IIFE,但话又说回来,我不知道它到底在调用什么,因为 passport.authenticate() 本身就是一个函数调用...或者不是?

最佳答案

它将参数传递给将返回的函数。

请检查源代码以获取更多信息并查看发生了什么。

passport/lib/middleware/authenticate.js

@Dijkie85,请原谅我,我一直很忙。

考虑:

function getFoo(arg1, arg2) {
return function getFoo(arg3, arg4) {
return (arg3 + arg4) || "foo";
}
}
console.log(getFoo()); // "Function: getFoo"
console.log(getFoo()()); // "foo"
console.log(getFoo()(1, 2)); // 3

在authenticate.js文件中你也处于同样的情况。为了简单起见,您可以删除逻辑并再次检查:

module.exports = function authenticate(passport, name, options, callback) {
return function authenticate(req, res, next) {
...
}
}

reqresnext由express提供返回函数。

关于javascript - 了解 Passport.authenticate ('local' ) 语法位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59985723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com