首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在NextAuth ()内部使用useSession()钩子

在NextAuth ()内部使用useSession()钩子
EN

Stack Overflow用户
提问于 2021-11-11 18:50:37
回答 2查看 1.1K关注 0票数 0

我正试图从我的服务器上获取一些数据,这取决于当前登录的是谁。我用的是Next-8月,通常我可以打电话给:

代码语言:javascript
复制
const { data: session } = useSession();

在functional的顶部,但是您不能在getServerSideProps()中这样做。

我需要这样的请求:

代码语言:javascript
复制
export async function getServerSideProps() {
  const res = await fetch(
    `http://localhost:5000/api/users/${session.id}/following`
  );
  const isFollowing = res.json();
  return {
    props: { props: isFollowing },
  };
}

它动态地输入当前用户会话ID。

如何在 getServerSideProps中访问会话ID getServerSideProps

EN

回答 2

Stack Overflow用户

发布于 2021-11-11 21:36:56

因为useSession是react,所以它只能在组件内部使用。对于服务器端的使用,另一种方法来自getSession。https://next-auth.js.org/v3/getting-started/client#getsession

服务器端示例

代码语言:javascript
复制
    import { getSession } from "next-auth/client"

    export default async (req, res) => {
      const session = await getSession({ req })
      /* ... */  
      res.end()
    }

注意:在调用getSession()服务器端时,需要传递{req}或上下文对象。

票数 2
EN

Stack Overflow用户

发布于 2021-11-11 19:03:19

您应该将头从getServerSideProps请求重新分配到内部fetch,因为该提取没有标头、cookie或令牌。

代码语言:javascript
复制
export async function getServerSideProps(ctx) {
  const headers=ctx.req.headers //where cookies, jwt or anything
  const res = await fetch(
    `http://localhost:5000/api/users/${session.id}/following`,
    {headers}
  );
  const isFollowing = res.json();
  return {
    props: { props: isFollowing },
  };
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69933445

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档