我正在使用nodejs,express和passport进行谷歌身份验证。我差不多完成但是我写了一个函数,如果用户没有登录,那么它应该重定向到主页,它不能正常工作。路由器文件中的代码如下:
var express = require('express');
var passport = require('passport');
var router = express.Router();
var User = require('../models/user.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'sprinklrExchange' });
});
router.get('/ask', function(req, res, next) {
res.render('index2', { title: 'sprinklrExchange' });
});
router.get('/profile', function(req, res, next) {
res.render('profile.ejs', { user: req.user });
});
router.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));
// the callback after google has authenticated the user
router.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect : '/profile',
failureRedirect : '/'
}));
router.get('/logout', function(req,res){
req.logout();
res.redirect('/');
});
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated()){
return next();
}
// console.log("hello world");
// if they aren't redirect them to the home page
res.redirect('/');
}
module.exports = router;
每当我在没有登录的情况下重定向到localhost:3000/profile
时,它会显示以下内容(而不是将我重定向到主页):
profile.ejs:
<!doctype html>
<html>
<head>
<title>Node Authentication</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<style>
body { padding-top:80px; word-wrap:break-word; }
</style>
</head>
<body>
<div class="container">
<div class="page-header text-center">
<h1><span class="fa fa-anchor"></span> Profile Page</h1>
<a href="/logout" class="btn btn-default btn-sm">Logout</a>
</div>
<div class="row">
<!-- GOOGLE INFORMATION -->
<div class="col-sm-6">
<div class="well">
<h3 class="text-danger"><span class="fa fa-google-plus"></span> Google</h3>
<p>
<strong>id</strong>: <%= user.google.id %><br>
<strong>token</strong>: <%= user.google.token %><br>
<strong>email</strong>: <%= user.google.email %><br>
<strong>name</strong>: <%= user.google.name %>
</p>
</div>
</div>
</div>
</div>
</body>
</html>
提前致谢。
答案 0 :(得分:0)
您遇到问题的原因是:
如果您在未登录的情况下访问localhost:3000/profile
,则req.user
未定义,因此您无法user.google.id
。