我正在处理一个使用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): console screenshot

推荐答案

我想这是因为在您登录浏览器后,一些会话会被存储并与您的请求一起发送.但是,在您的服务器组件中,情况并非如此.

从服务器组件获取内部API路由无论如何都是一件坏事.因为它已经在服务器上运行,所以直接从数据库中获取数据.否则,你很可能会得到TypeError: fetch failed during Next.js project build分.

此外,来自Vercel的Lee Robinson解释说,在这段名为10 common mistakes with the Next.js App Router的视频中.

Javascript相关问答推荐

使用TMS Web Core中的HTML模板中的参数调用过程

如何判断属于多个元素的属性是否具有多个值之一

了解Node.js中的EventEums和浏览器中的addEventEums之间的关系

在nextjs服务器端api调用中传递认证凭证

Chromium会将URL与JS一起传递到V8吗?

如何从html元素创建树 struct ?

如何将Openjphjs与next.js一起使用?

类构造函数忽略Reaction Native中的可选字段,但在浏览器中按预期工作

无法避免UV:flat的插值:非法使用保留字"

为什么云存储中的文件不能公开使用?

使用线性插值法旋转直线以查看鼠标会导致 skip

如何根据输入数量正确显示alert ?

每隔3个项目交替显示,然后每1个项目交替显示

在Puppeteer中使用promise进行日志(log)记录时出现TargetCloseError

对不同目录中的Angular material 表列进行排序

我如何才能获得价值观察家&对象&S的价值?

更改管线时不渲染组件的react

使用Java脚本替换字符串中的小文本格式hashtag

Rails 7:在不使用导入映射的情况下导入Java脚本

如何为Reaction应用程序创建仅登录的路由?