我正试图从我的服务器上获取一些数据,这取决于当前登录的是谁。我用的是Next-8月,通常我可以打电话给:
const { data: session } = useSession();在functional的顶部,但是您不能在getServerSideProps()中这样做。
我需要这样的请求:
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
发布于 2021-11-11 21:36:56
因为useSession是react,所以它只能在组件内部使用。对于服务器端的使用,另一种方法来自getSession。https://next-auth.js.org/v3/getting-started/client#getsession
服务器端示例
import { getSession } from "next-auth/client"
export default async (req, res) => {
const session = await getSession({ req })
/* ... */
res.end()
}注意:在调用getSession()服务器端时,需要传递{req}或上下文对象。
发布于 2021-11-11 19:03:19
您应该将头从getServerSideProps请求重新分配到内部fetch,因为该提取没有标头、cookie或令牌。
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 },
};
}https://stackoverflow.com/questions/69933445
复制相似问题