我最近已将服务器项目从javascript切换为打字稿,并且正在清理一些代码。我曾经将一些Google护照Oauth资料和登录路线保存在单独的文件中,但决定将它们组合在一起。在此过程中,我破坏了一些代码,并且不明白为什么会发生错误或如何修复该错误。预先感谢!
我知道错误发生在server.express.use(auth.initialize())
行的index.ts中。我收到错误消息UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'initialize' of undefined
,您能帮我发现我在做什么吗?
index.ts
import { createTypeormConn } from './db/createConn'
import schema from './graphql'
import { pubsub } from './graphql/PubSub'
import * as auth from './middleware/auth'
const express = require('express')
const { GraphQLServer, PubSub } = require('graphql-yoga')
const cookieSession = require('cookie-session')
const cors = require('cors')
const path = require('path')
export const startServer = async () => {
await createTypeormConn()
const corsOptions = {
origin: [
//omitted for brevity
],
credentials: true
}
const options = {
port: process.env.PORT || 1337,
endpoint: '/api',
subscriptions: '/api',
playground: '/playground'
}
const server = new GraphQLServer({
schema,
context: req => ({ pubsub, request: req.request })
})
server.express.use(
cookieSession({
maxAge: 24 * 60 * 60 * 1000,
keys: [''] //omitted
})
)
server.use(cors(corsOptions))
server.express.options('/api', cors(corsOptions))
server.express.use(auth.initialize()) //fails during initialize
server.express.use(auth.session())
server.express.use('/auth', auth.routes)
server.express.use('/', express.static(path.join(__dirname, 'site')))
server.start(options, ({ port }) => {
console.log(`Server is running on localhost:${port}`)
})
}
startServer()
身份验证
import { User } from '../db/orm'
import * as passport from 'passport'
import { Router } from 'express'
import { OAuth2Strategy } from 'passport-google-oauth'
passport.serializeUser<any, any>((user, done) => {
done(null, user.id)
})
passport.deserializeUser((id, done) => {
User.findOne(id).then(user => {
done(null, user)
})
})
passport.use(
new OAuth2Strategy(
{
callbackURL: '/auth/google/redirect',
clientID:'', //omitted
clientSecret: '' //omitted
},
async (accessToken, refreshToken, profile, done) => {
//omitted
return done(null, user)
}
)
)
const routes = Router()
routes.get('/google/start', (req, res) => {
passport.authenticate('google', {
scope: ['profile'],
state: req.query.stream
} as any)(req, res)
})
routes.get('/google/redirect', passport.authenticate('google'), (req, res) => {
//omitted
})
const initialize = passport.initialize
const session = passport.session
export { initialize, session, routes }
答案 0 :(得分:0)
您正在丢失this
的{{1}}上下文。替换:
passport
具有:
const initialize = passport.initialize
const session = passport.session