我在为Next.js 13‘S app路由而苦苦挣扎.例如,当我试图从Postmann访问时,它总是给我一个404 Not Found.

我有这样的文件 struct :

enter image description here

例如,我的一个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: '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' });
    }
}

当我发送GET localhost:3000/api/admin/all时,它总是以404响应.找不到错误所在.

我try 了其他文件或文件夹命名.从我自己的应用程序打电话,使用curl命令,或使用postman .我的其他API路径也提供相同的404.

推荐答案

API路由应位于名为route.js的文件中.意思是app/api/admin/all.js应该是app/api/admin/route.js.此外,内部的函数应该使用特定的定义:

export async function GET(request) {}

GET可以替换为POSTPUTPATCH等.在您的情况下,它将是:

// 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: 400,
    }
  );
}

// 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,
      }
    );
  }
}

Javascript相关问答推荐

错误:找不到react-redux上下文值;请确保该组件包装在React原生Expo应用程序中的提供者中

以逗号分隔的列表来数组并填充收件箱列表

在shiny 模块中实现JavaScript

如何在不使用类型化数组的情况下将32位浮点数按位转换为整值?

强制执行useStatego struct 化变量[foo,setFoo]的命名约定?

有什么(最佳)方法可以从模块中获取脚本模块的多姆元素吗?

materialized - activeIndex返回-1

每次子路由重定向都会调用父加载器函数

Angular中计算信号和getter的区别

未捕获错误:在注销后重定向到/login页面时找不到匹配的路由

使用useEffect,axios和useParams进行react测试

给定一个凸多边形作为一组边,如何根据到最近边的距离填充里面的区域

在服务器上放置了Create Reaction App Build之后的空白页面

在Three JS中看不到补间不透明度更改效果

在使用HighChats时如何避免Datatables重新初始化错误?

Angular 中的类型错误上不存在获取属性

为什么JPG图像不能在VITE中导入以进行react ?

回溯替代方式

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

我怎样才能得到一个数组的名字在另一个数组?