我正在处理一个使用next.js中的auth.js进行用户身份验证的项目.我想有一个API,从MongoDB数据库中获取关于用户的特定信息.
该站点通过next.js中的中间件进行保护.如果我在登录后直接访问URL(本地主机:3000/api/Project),我的API就可以工作.
然而,当我try 获取数据时,我得到了一个错误Error: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
,因此似乎有一个重定向到了某个地方,但我找不到原因.
这是我的api/Projects/route.js
import { connectDB } from "../../../utils/database";
import { NextResponse } from "next/server";
import Project from "../../(models)/Project";
import { getServerSession } from "next-auth";
import { options } from "../../api/auth/[...nextauth]/options";
export const GET = async (req, res) => {
const session = await getServerSession(options);
try {
await connectDB();
const fetchedProjects = await Project.find({
userID: session.user.id,
}).exec();
return new NextResponse(JSON.stringify(fetchedProjects), { status: 200 });
} catch (error) {
return new NextResponse("Error in fetching data" + error, { status: 500 });
}
};
这是我的app/projects/page.js
中的API FETCH
async function getProjects() {
try {
console.log("FETCHING DOCUMENTS");
const res = await fetch("http://localhost:3000/api/Projects", {
cache: "no-store",
});
if (!res.ok) return notFound();
console.log(res);
return res.json();
} catch (error) {
console.log(error);
}
};
If I bypass all my authentication and just fetch all entries from the database in my API this code works. With the authentication in place fetch returns the following (taken from the console):