【问题标题】:Nextjs Api endpoint is not executing middlewareNextjs Api 端点未执行中间件
【发布时间】:2021-06-29 18:15:14
【问题描述】:

我有一个 api 端点,它运行一些 passport.js 中间件并在登录时返回一个用户对象。

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

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

/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

/页面/帐户

...
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 next.js passport.js


    【解决方案1】:

    您不应使用 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

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 1970-01-01
      • 2021-08-19
      • 2020-09-25
      • 2021-01-06
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2020-08-10
      相关资源
      最近更新 更多