gpt4 book ai didi

javascript - 用户注册后登录用户

转载 作者:行者123 更新时间:2023-12-02 22:23:37 24 4
gpt4 key购买 nike

我正在阅读一篇关于使用 Passport 本地 Mongoose 进行身份验证的文章。 Article

在本文中,我发现这行代码可以注册用户并登录

app.post('/register', function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}

passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});

让我困惑的部分是这个

passport.authenticate('local')(req, res, function () {
res.redirect('/');
});

首先,我不明白 passport.authenticate() 之后的部分。它看起来不像回调或 IIFE。其次,据我所知, passport.authenticate() 是一个中间件(如果我错了,抱歉)。我们应该将它用作这样的函数吗?

对此我最好的解释是因为在文章中已经定义了上面

passport.use(new LocalStrategy(Account.authenticate()))

因此,passport.authenticate() 现在将调用 Account.authenticate()。奇怪的是,authenticate() 需要密码,但我们没有提供密码。也许它会返回一个 Promise,但是我上面说的部分看起来不像一个 Promise。

那么这部分是什么?实际登录用户是否是一个好习惯?

最佳答案

让我们先谈谈那个奇怪的部分:

TLDR:正如第一个评论者提到的passport.authenticate 返回一个函数

我们如何调用函数?像这样:functionName(param1, param2,callbackMaybe);。您认为这没有问题吗?

现在,看看下面的代码

function a() {
return function b() {
console.log("Hi there!");
}
}

函数a返回函数b。您将如何在控制台中显示 Hi There! ?你必须像a()()那样做。您可以通过以下方式查看:

let b = a(); // Since, a returns a function so, b is now a function.
b();

同样,passport.authenticate('local') 返回一个带有 3 个参数的函数,其中最后一个是回调函数。就表达而言,第三个参数是 next() 函数。我相信你知道next()函数的用法。您正在发送 function () { res.redirect('/'); } 作为回调。此回调将您重定向到此 '/' 路由。

问题的第二部分

现在,我没有看到任何网站在注册后自动登录的用户。

希望有帮助。

关于javascript - 用户注册后登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59138766/

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