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

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

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 文件如下:

  1. import { PrismaClient } from '@prisma/client';
  2. const prisma = new PrismaClient();
  3. export default async function all(req, res) {
  4. if (req.method !== 'GET') {
  5. return res.status(405).json({ error: '不允许的方法' });
  6. }
  7. try {
  8. // 使用 Prisma 获取所有管理员
  9. const admins = await prisma.admin.findMany();
  10. return res.status(200).json(admins);
  11. }
  12. catch (error) {
  13. return res.status(500).json({ error: '获取管理员失败' });
  14. }
  15. }

当我发送 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:

  1. import { PrismaClient } from '@prisma/client';
  2. const prisma = new PrismaClient();
  3. export default async function all(req, res) {
  4. if (req.method !== 'GET') {
  5. return res.status(405).json({ error: 'Method not allowed' });
  6. }
  7. try {
  8. // Get all admins using Prisma
  9. const admins = await prisma.admin.findMany();
  10. return res.status(200).json(admins);
  11. }
  12. catch (error) {
  13. return res.status(500).json({ error: 'Failed to get admins' });
  14. }
  15. }

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。此外,函数内部应该使用特定的定义:

  1. export async function GET(request) {}

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

  1. // 请注意NextResponse的导入位置:
  2. import { NextResponse } from "next/server";
  3. import { PrismaClient } from "@prisma/client";
  4. const prisma = new PrismaClient();
  5. // 请注意函数定义:
  6. export async function GET(req) {
  7. return NextResponse.json(
  8. { error: "Method not allowed" },
  9. {
  10. status: 405
  11. }
  12. );
  13. }
  14. // 请注意函数定义:
  15. export async function POST(req) {
  16. try {
  17. // 使用Prisma获取所有管理员
  18. const admins = await prisma.admin.findMany();
  19. return NextResponse.json(admins, {
  20. status: 200,
  21. });
  22. } catch (error) {
  23. return NextResponse.json(
  24. { error: "Failed to get admins" },
  25. {
  26. status: 500,
  27. }
  28. );
  29. }
  30. }
英文:

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:

  1. export async function GET(request) {}

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

  1. // Notice from where NextResponse is imported:
  2. import { NextResponse } from "next/server";
  3. import { PrismaClient } from "@prisma/client";
  4. const prisma = new PrismaClient();
  5. // Notice the funciton definiton:
  6. export async function GET(req) {
  7. return NextResponse.json(
  8. { error: "Method not allowed" },
  9. {
  10. status: 405
  11. }
  12. );
  13. }
  14. // Notice the funciton definiton:
  15. export async function POST(req) {
  16. try {
  17. // Get all admins using Prisma
  18. const admins = await prisma.admin.findMany();
  19. return NextResponse.json(admins, {
  20. status: 200,
  21. });
  22. } catch (error) {
  23. return NextResponse.json(
  24. { error: "Failed to get admins" },
  25. {
  26. status: 500,
  27. }
  28. );
  29. }
  30. }

答案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:

确定