我正在编写一个应用程序,该应用程序实际上将列出产品并允许用户结帐他们的购物车。但是我在使用Passport进行用户身份验证时遇到了这个问题。我的Facebook身份验证工作正常,可以捕获用户的电子邮件地址等。我一直在与Twitter斗争,谷歌将bacxk重定向到本地主机(当前在笔记本电脑上工作)。重定向到localhost后,出现以下错误:
TypeError:无法读取未定义的属性“ 0”
我的facebook.js护照文件如下所示,并且工作正常
'use strict'
const passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy
const User = require('../models/user')
let check = x => x === undefined ? 'empty' : x
passport.use(new FacebookStrategy({
clientID: 'xxxxxxxxxxxxx',
clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxx',
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({
id: profile.id,
name: profile.displayName,
photo: "https://graph.facebook.com/"+profile.id+"/picture",
email: check(profile._json.email)
}, function(err, user) {
return done( err, user)
})
}
))
我的twitter.js和google.js文件如下所示:
'use strict'
const passport = require('passport')
, TwitterStrategy = require('passport-twitter').Strategy
const User = require('../models/user')
passport.use(new TwitterStrategy({
consumerKey: 'xxxxxxxxxxxxxxxxx',
consumerSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
callbackURL: "http://localhost:3000/auth/twitter/callback",
includeEmail: true
},
function(token, tokenSecret, profile, done) {
User.findOrCreate({
id: profile.id,
name: profile.displayName,
photo: profile.photos[0].value,
email: profile.emails[0].value
}, function(err, user) {
return done(err, user)
})
}
))
'use strict'
const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
const User = require('../models/user')
passport.use(new GoogleStrategy({
clientID: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
callbackURL: "http://localhost:3000/auth/google/callback",
profileFields: ['id', 'displayName', 'photos', 'email']
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({
id: profile.id,
name: profile.displayName,
photo: profile.photos[0].value,
email: profile.emails[0].value
}, function (err, user) {
return done(err, user)
})
}
))
我的app.js如下所示:
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const favicon = require('serve-favicon')
const path = require('path')
const app = express()
const{mongoose} = require('./db/index')
const passport = require('passport')
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
//================ROUTES
const userRouter = require('./routes/index')
const adminRouter = require('./routes/admin')
const productRouter = require('./routes/products')
//=================MODELS
const Category = require('./models/category')
const Product = require('./models/product')
const User = require('./models/user')
app.set('view engine', 'ejs')
const logger = require('./log')
const morgan = require('morgan')
app.use(express.static(path.join(__dirname,'public')))
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(morgan('dev'))
app.use(morgan('combined',{'stream': logger.stream}))
//==================SESSIONS
app.use(session({
secret: 'secret',
saveUninitialized: false,
resave: false,
store: new MongoStore({url: 'mongodb://localhost/e-commerce'})
}))
app.use(passport.initialize())
app.use(passport.session())
//==================Navbar
app.use((req,res,next) => {
Category.find().then(data => {
res.locals.ctg = data
next()
}, (e) => {throw new Error('Unable to find category')})
})
//==================Use Routes
app.use(userRouter)
app.use(adminRouter)
app.use(productRouter)
//======================PASSPORT
passport.serializeUser(function (user, done) {
done(null, user._id)
})
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user)
})
})
//==================Errors
app.use(function(req,res,next){
const err = new Error('Not found')
err.status = 404
next(err)
})
app.use(function(err,req,res,next){
res.locals.error = req.app.get('env') === 'development' ? err : {}
res.status(err.status || 500)
res.render('error')
})
//app.set('port',(process.env.PORT || 3000))
const PORT = process.env.PORT || 3000
app.listen(PORT,() => logger.info(`${String.fromCodePoint(9749)} is ready on port ${PORT}`))
// app.listen(app.get('port'),function(){
// console.log('running on port',app.get('port'))
// })
module.exports ={app}
和我的products.js如下所示,其中添加了路由:
'use strict'
const router = require('express').Router()
const logger = require('../log')
const Category = require('../models/category')
const Product = require('../models/product')
router.get('/navbar', (req,res) => {
const perPage = 8
const page = req.query.page || 1
const ctg = req.query.name
Product.find({category: req.query.name})
.skip((perPage * page) - perPage)
.limit(perPage)
.then(products => {
Product.count({category: req.query.name})
.then(count => {
res.render('product', {
navbar: products,
current: page,
pages: Math.ceil(count / perPage),
category: ctg
})
}, (e) => {throw new Error('Unable to count!')})
}, (e) => {throw new Error('Unable to find this product!')})
})
router.get('/single', (req,res) => {
if (req.isAuthenticated()){
console.log(req.user)
res.send('ok')
}
})
module.exports = router
尝试使用Twitter时,控制台出现以下错误:
GET /auth/twitter 302 855.274 ms - 0
{"message":"::1 - - [25/Mar/2019:14:24:58 +0000] \"GET /auth/twitter HTTP/1.1\" 302 0 \"http://localhost:3000/login\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/twitter/callback?oauth_token=xxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxx 500 1393.641 ms - 1775
{"message":"::1 - - [25/Mar/2019:14:25:00 +0000] \"GET /auth/twitter/callback?oauth_token=xxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxx HTTP/1.1\" 500 1775 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/twitter/style.css 404 11.922 ms - 1735
{"message":"::1 - - [25/Mar/2019:14:25:00 +0000] \"GET /auth/twitter/style.css HTTP/1.1\" 404 1735 \"http://localhost:3000/auth/twitter/callback?oauth_token=xxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxx\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
,当尝试使用Google时,我得到以下信息:
GET /auth/google 302 7.842 ms - 0
{"message":"::1 - - [25/Mar/2019:14:05:38 +0000] \"GET /auth/google HTTP/1.1\" 302 0 \"http://localhost:3000/login\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/google/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/profile.emails.read 500 1031.758 ms - 1775
{"message":"::1 - - [25/Mar/2019:14:05:54 +0000] \"GET /auth/google/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/profile.emails.read HTTP/1.1\" 500 1775 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/google/style.css 404 13.095 ms - 1735
{"message":"::1 - - [25/Mar/2019:14:05:54 +0000] \"GET /auth/google/style.css HTTP/1.1\" 404 1735 \"http://localhost:3000/auth/google/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/profile.emails.read\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
GET /auth/google/favicon.ico 404 4.848 ms - 1735
{"message":"::1 - - [25/Mar/2019:14:05:54 +0000] \"GET /auth/google/favicon.ico HTTP/1.1\" 404 1735 \"http://localhost:3000/auth/google/callback?code=4/xxxxxxxxxxxxxxxxxxxxxxxxx&scope=profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/profile.emails.read\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"\n","level":"info"}
请告知我是否需要其他信息来帮助我在此处通过代码识别问题。