我正在使用next-auth
的next 13
。当我使用getServerSession(req, res, authOptions)
验证API以检查用户是否登录时,出现错误TypeError: res.getHeader is not a function
下面是我的API
用户/路由.ts
import { NextRequest, NextResponse } from 'next/server'
import { connectMongoDB } from "@/lib/mongodb";
import User from "@/models/user"
import { getServerSession } from 'next-auth';
import { authOptions } from '../auth/[...nextauth]/route';
export async function GET(req: NextRequest, res: NextResponse) {
const session = await getServerSession(req, res, authOptions)
if (!session) {
return NextResponse.json({ message: "You must be logged in.", status: 401 });
}
try {
await connectMongoDB();
const users = await User.find();
return NextResponse.json({ message: "", status: 200, data: users })
} catch (error) {
return NextResponse.json({ message: "Error occured..", status: 500 })
}
}
auth/[...nextauth]/routes.js
import { connectMongoDB } from "@/lib/mongodb";
import User from "@/models/user";
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
export const authOptions = {
providers: [
CredentialsProvider({
name: "Email and password",
credentials: {},
async authorize(credentials, req) {
const { email, password } = credentials;
try {
await connectMongoDB();
const user = await User.findOne({ email })
if (!user) {
return null;
}
const passwordMatch = await bcrypt.compare(password, user.password)
if (!passwordMatch) {
return null;
}
return user;
} catch (error) {
console.log('error', error)
return null;
}
},
}),
],
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: "/",
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
我试过getServerSession(authOptions)
和它的工作,但不知道这是正确的方式或没有。
请帮助我以正确的方式理解/解决此问题
1条答案
按热度按时间9fkzdhlc1#
getServerSession(authOptions)
工作得很好。如果要包含请求,必须将
headers
与authOptions
一起沿着到getServerSession
函数中。