获取应用程序目录中的 Next.js API 路由会返回 404 找不到。

huangapple go评论66阅读模式
英文:

Fetching Next.js API Route in the app directory gives 404 Not Found

问题

我在处理 Next.js 13 的 app 路由时遇到了问题。每当我尝试从 Postman 等工具访问时,它总是返回 404 Not Found。

我有以下文件结构:

获取应用程序目录中的 Next.js API 路由会返回 404 找不到。

例如,我的其中一个 API 文件如下:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function all(req, res) {
    if (req.method !== 'GET') {
        return res.status(405).json({ error: '不允许的方法' });
    }

    try {
        // 使用 Prisma 获取所有管理员
        const admins = await prisma.admin.findMany();

        return res.status(200).json(admins);
    }
    catch (error) {
        return res.status(500).json({ error: '获取管理员失败' });
    }
}

当我发送 GET localhost:3000/api/admin/all 时,它总是返回 404。我找不到错误在哪里。

我尝试了其他文件或文件夹命名方式。从我的应用程序中调用,使用 curl 命令,或者使用 Postman。我的其他 API 路由也返回相同的 404 错误。

英文:

I am struggling with Next.js 13's app routing. It always gives me a 404 Not Found when I try to access fromPostmann for example.

I have this file structure:

获取应用程序目录中的 Next.js API 路由会返回 404 找不到。

And for example, one of my API files is:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function all(req, res) {
    if (req.method !== 'GET') {
        return res.status(405).json({ error: 'Method not allowed' });
    }

    try {
        // Get all admins using Prisma
        const admins = await prisma.admin.findMany();

        return res.status(200).json(admins);
    }
    catch (error) {
        return res.status(500).json({ error: 'Failed to get admins' });
    }
}

When I send a GET localhost:3000/api/admin/all it always responds with a 404. Couldn't find where is the error.

I tried other file or folder namings. Calling from my own app, using the curl command, or using Postman. My other API routes give the same 404.

答案1

得分: 5

API路由应该存储在名为route.js的文件中。意味着app/api/admin/all.js应该改为app/api/admin/route.js,对应的URL应为/api/admin。此外,函数内部应该使用特定的定义:

export async function GET(request) {}

GET可以替换为POSTPUTPATCH等。在你的情况下,它应该是:

// 请注意NextResponse的导入位置:
import { NextResponse } from "next/server";

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

// 请注意函数定义:
export async function GET(req) {
  return NextResponse.json(
    { error: "Method not allowed" },
    {
      status: 405
    }
  );
}

// 请注意函数定义:
export async function POST(req) {
  try {
    // 使用Prisma获取所有管理员
    const admins = await prisma.admin.findMany();

    return NextResponse.json(admins, {
      status: 200,
    });
  } catch (error) {
    return NextResponse.json(
      { error: "Failed to get admins" },
      {
        status: 500,
      }
    );
  }
}
英文:

An API Route should be in a file called route.js. Meaning app/api/admin/all.js should be app/api/admin/route.js, with the corresponding URL being /api/admin. Also, the functions inside should use a specific definition:

export async function GET(request) {}

GET, can be replaced with POST, PUT, PATCH, etc. In your case, it would be:

// Notice from where NextResponse is imported:
import { NextResponse } from "next/server";

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

// Notice the funciton definiton:
export async function GET(req) {
  return NextResponse.json(
    { error: "Method not allowed" },
    {
      status: 405
    }
  );
}

// Notice the funciton definiton:
export async function POST(req) {
  try {
    // Get all admins using Prisma
    const admins = await prisma.admin.findMany();

    return NextResponse.json(admins, {
      status: 200,
    });
  } catch (error) {
    return NextResponse.json(
      { error: "Failed to get admins" },
      {
        status: 500,
      }
    );
  }
}

答案2

得分: 0

除了Youssouf的回答(我觉得非常有帮助),如果你在获取request.body的内容时遇到问题,可以使用const body = await request.json()来获取请求体。

https://developer.mozilla.org/en-US/docs/Web/API/Request/json

英文:

In addition to Youssouf's answer (which I found very helpful), if you have problems getting the content of request.body, use const body = await request.json() to get the body.

https://developer.mozilla.org/en-US/docs/Web/API/Request/json

huangapple
  • 本文由 发表于 2023年5月26日 08:19:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76336930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定