【问题标题】:Using Passport.js with Typescript将 Passport.js 与 Typescript 一起使用
【发布时间】:2021-01-20 16:46:44
【问题描述】:

这是我的护照本地配置。我将它包装在一个函数中,以便我可以在其他地方使用它:

export const LocalPassport = (passport: any, strategy: any) => {
  passport.use(
    new strategy(
      {
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true,
        session: false,
      },
      async (req: Request, email: string, password: string, done: any) => {
        try {
          const user = await AuthService.findUserByEmail(email)

          if (!user) {
            return done(null, false)
          }

          const passCheck = bcrypt.compare(password, user.password)
          if (!passCheck) {
            return done(null, false)
          }

          return done(null, user)
        } catch (error) {
          console.log(error)
        }
      }
    )
  )
}

我在我的登录路由器中使用它:

import express from 'express'
import passport from 'passport'
import Strategy from 'passport-local'
import bodyParser from 'body-parser'

import { createUser } from '../controllers/auth'
import FormValidate from '../middlewares/FormValidate'
import { LocalPassport } from '../config/passport'

import User from '../models/User'

LocalPassport(passport, Strategy.Strategy)

const router = express.Router()
router.use(passport.initialize())
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())

//**path for api/v1/auth */
router.post('/register', FormValidate.register, createUser)
router.post('/login', passport.authenticate('local'), async (req, res) => {
  try {
    res.send('logged in')
  } catch (error) {
    console.log(error)
  }
})

export default router

当我从邮递员那里测试这条路线时,我收到了一长串错误,但它以:RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined 我试过 console.log 并且我可以看bcrypt比较返回true,我相信错误发生在done被调用之后

我在这里做错了什么?我应该如何替换护照配置文件中的any 类型。感谢您的帮助。

【问题讨论】:

    标签: javascript typescript express passport.js


    【解决方案1】:

    所以我认为错误是因为我没有为护照设置会话,并且在身份验证后它尝试设置会话,因此出现错误。我通过以下方式解决了这个问题:

    router.post('/login', passport.authenticate('local', {session: false}), async (req, res) => {
      try {
        res.send('logged in')
      } catch (error) {
        console.log(error)
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-19
      • 2019-06-06
      • 2015-03-09
      • 2012-12-14
      • 2016-08-24
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多