我正在尝试使用res.redirect将用户重定向到路由,或者如果他们尝试使用指定的域以外的域登录,则使用res.send发送文件。条件检查正在运行,但我正在尝试使用res.sendFile / res.redirect,但它似乎不在此函数的范围内工作。很明显,这个功能没有资源,但这就是我想到的一切。有一个非常好的在线搜索,但我还没有解决问题。
任何帮助表示赞赏。
passport.use(
new GoogleStrategy({
callbackURL: '/google/redirect',
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret
}, function (accessToken, refreshToken, profile, done){
if (profile._json.hd === "HIDDEN-DOMAIN.COM") {
User.findOne({googleId : profile.id})
.then(function(currentUser){
if(currentUser){
console.log('User with ID' + currentUser.googleId +' already exists. No new entry was made');
done(null, currentUser);
} else {
new User({
username: profile.displayName,
googleId: profile.id
})
.save()
.then(function(newUser){
console.log('New user created: ' + newUser);
done(null, newUser);
});
}
})
} else {
console.log(__dirname);
res.sendFile('../login.html');
};
}));
使用中间件执行检查,如果通过则使用next()
。结帐:https://expressjs.com/en/guide/using-middleware.html
此示例显示了安装在/ path上的中间件功能。对/ path上的任何类型的HTTP请求执行该函数。
此示例显示了路由及其处理函数(中间件系统)。该函数处理GET请求。
app.use('/', function (req, res, next) {
// Check 1
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
// Check 2: Pass first check
console.log('Request Type:', req.method)
next()
})
app.get('/', (req, res) => {
// Final Route
});
例:
app.use('/first', function (req, res, next) {
passport.use(
new GoogleStrategy({
callbackURL: '/google/redirect',
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret
}, function (accessToken, refreshToken, profile, done){
if (profile._json.hd === "HIDDEN-DOMAIN.COM") {
User.findOne({googleId : profile.id})
.then(function(currentUser){
if(currentUser){
console.log('User with ID' + currentUser.googleId +' already exists. No new entry was made');
done(null, currentUser);
} else {
new User({
username: profile.displayName,
googleId: profile.id
})
.save()
.then(function(newUser){
console.log('New user created: ' + newUser);
done(null, newUser);
next(); // next();
});
}
})
} else {
console.log(__dirname);
next(); // next();
}
}));
}, function (req, res, next) {
// More checks
next()
});
app('/', (req, res) => {
// final route here
res.sendFile('../login.html');
})