我正在尝试从我的服务器获取一些数据,具体取决于当前登录的用户。我正在使用 Next-Auth,通常我可以调用:
const { data: session } = useSession();
位于功能组件的顶部,但您不能在
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。
如何访问我的会话 ID 内部
getServerSideProps
?
由于 useSession 是react-hook - 它只能在组件内部使用。对于服务器端使用,Next-Auth 包中还有另一种方法 - 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} 或 context 对象。
您应该将
getServerSideProps
请求中的标头重新分配给内部提取,因为该提取没有标头、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 },
};
}
此方法已在
getServerSession
的 v4
中重命名为 NextAuth
- 请参阅
https://next-auth.js.org/configuration/nextjs#getserversession。以下是一些如何导入和使用它的示例代码:
//you must import your NextAuth options. Here is an example path
import { authOptions } from '../app/api/auth/[...nextauth]/route'
import { getServerSession } from "next-auth"
// This gets called on every request
export async function getServerSideProps(context) {
const session = await getServerSession(context.req, context.res, authOptions)
//now you can use session to pass to an api - this is not real
const mydata = await fetch(`http://localhost/example/${session.id}`);
// Pass data to the page via props
return { props: { mydata } }
}