0

我正在使用 Next.js 并成功添加了 passport.js,从而在成功登录后让用户返回。\0/

但是我想要的是req.user可用于我的api/user路由...

在中间件/auth.js 中的这个示例仓库中

use.()它在下面的函数中提到...

Initialize mocked database 添加自己的数据库后删除它

import nextConnect from 'next-connect'
import passport from '../lib/passport'
import session from '../lib/session'

const auth = nextConnect()
  .use(
    session({
      name: 'sess',
      secret: process.env.TOKEN_SECRET,
      cookie: {
        maxAge: 60 * 60 * 8, // 8 hours,
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        path: '/',
        sameSite: 'lax',
      },
    })
  )
  .use((req, res, next) => {
 // Initialize mocked database
 // Remove this after you add your own database
    req.session.users = req.session.users || []
    next()
  })
  .use(passport.initialize())
  .use(passport.session())

export default auth

这是我的api/user路线:

import nextConnect from 'next-connect'
import auth from '../../middleware/auth'

const handler = nextConnect()

handler
  .use(auth)
  .get((req, res) => {
    // You do not generally want to return the whole user object
    // because it may contain sensitive field such as !!password!! Only return what needed

    // const { _id } = req.user
    // res.json({ user: { _id } })
    console.log("in api/user req.user ", req.user); // returns undefined.

    if (req.user) {
      const { _id } = req.user
      res.json({ user: { _id } })
    } else {
      res.json({ user: null })
    }
  })


export default handler;

我的理由是 repo 也有一个钩子,它调用/api/user路由来查看req.user 是否存在......

import useSWR from 'swr'

export const fetcher = (url) => fetch(url).then((r) => r.json())

export function useUser() {
  const { data, mutate } = useSWR('/api/user', fetcher)
  // if data is not defined, the query has not completed

  console.log("data in useUser hooks!", data);

  console.log("data?.user ", data?.user);
  const loading = !data
  const user = data?.user
  return [user, { mutate, loading }]
}

根据 repo 的内容,您应该能够通过在文件中设置数据库来获取req.usermiddleware/auth ,您将如何执行此操作并因此在api/user路由中获取它?

4

1 回答 1

0

而不是使用 req.user 使用 req.session 然后 console.log 这个

于 2022-02-14T12:52:14.263 回答