Next.js(TypeScript)报错:GetServerSideProps无'req'/'res'属性
解决Next-auth getServerSideProps中context.req/res类型报错问题
你的报错根源在于context参数的类型声明错误:你把GetServerSideProps(这是整个服务器端props函数的类型)当成了context对象的类型,而context实际的类型应该是GetServerSidePropsContext。
修正步骤:
- 从Next.js中导入
GetServerSidePropsContext类型 - 将getServerSideProps的context参数类型替换为
GetServerSidePropsContext
修正后的完整代码:
import React from "react"; import type { GetServerSideProps, GetServerSidePropsContext } from "next"; import { getServerSession } from "next-auth/next"; import { authOptions } from "../../pages/api/auth/[...nextauth]"; function EditProfile() { return ( <> .... </> ); } export async function getServerSideProps(context: GetServerSidePropsContext) { const session = await getServerSession(context.req, context.res, authOptions); return { props: { session }, // 建议把session传入组件props供使用 }; } export default EditProfile;
另一种更规范的写法(指定整个函数的类型):
你也可以不单独声明context的类型,直接给getServerSideProps函数指定GetServerSideProps类型,TypeScript会自动推断context的正确类型:
export const getServerSideProps: GetServerSideProps = async (context) => { const session = await getServerSession(context.req, context.res, authOptions); return { props: { session }, }; };
以上两种写法都能彻底解决req/res属性不存在的类型报错问题。
内容的提问来源于stack exchange,提问作者Tsabary
相关产品推荐
相关产品推荐

