Nextjs Api 端点未执行中间件

Nextjs Api endpoint is not executing middleware

我有一个 api 端点,它运行一些 passport.js 中间件和 returns 一个用户对象(如果已登录)。

当我通过浏览器访问端点时它可以工作,但是当我在 getServerSideProps 中使用 fetch 时,它 returns 为空。

中间件似乎没有执行...有什么想法吗?

/api/auth/loggedin

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

const handler = nextConnect()

handler
  .use(auth)
  .get((req, res) => {
    console.log(req.user)
    res.json({ user: req.user })
  })

export default handler

/pages/account

...
export async function getServerSideProps(context)  {
  let res = await fetch(`${baseurl}/api/auth/loggedin`)
  res = await res.json()

  console.log(res)
  return {
    props: {}, // Will be passed to the page component as props
  }
}

您不应使用 fetch 在 getServerSidePropsgetStaticPropsgetStaticPaths 中调用您自己的 API。代码始终在服务器端执行,因此您应该直接调用方法而不是 api.

这可能是您想要在客户端执行的操作?在那里做抓取就可以了。

何时使用 getServerSideProps:https://nextjs.org/docs/basic-features/data-fetching#when-should-i-use-getserversideprops

不要在 getServerSideProps 等内部获取:https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly