类型错误:路由“src/app/api/orders/route.ts”与 Next.js 路由所需的类型不匹配。 “默认”不是有效的路线导出字段

问题描述 投票:0回答:1

我想使用 Prisma 使用用户的电子邮件查找数据库中的订单(它们仅通过 Google 提供商登录)。这是存储库 - https://github.com/Jayesh-kahnani/Snatch

这是API。

// src/app/api/order/route.ts
import { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../../../lib/prisma";
import { getSession } from "next-auth/react"; // Import getSession from next-auth/react

export default async function (req: NextApiRequest, res: NextApiResponse) {
  try {
    const session = await getSession({ req }); // Get the session object from the request

    if (!session) {
      return res.status(401).json({ error: "Unauthorized" });
    }

    if (req.method !== "GET") {
      return res.status(405).json({ error: "Method Not Allowed" });
    }

    const userId = session.user?.email; // Get the user's email from the session

    if (!userId) {
      return res.status(400).json({ error: "User ID not found in session" });
    }

    const orders = await prisma.post.findMany({
      where: {
        author: { email: userId }, // Filter orders by user's email
        published: true, // Filter based on your criteria
      },
      include: {
        author: { select: { name: true } },
      },
    });

    res.status(200).json({ orders });
  } catch (error) {
    console.error("Error fetching orders:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
}

这是页面组件:

// src/app/user-orders/page.tsx
"use client"
import { useState, useEffect } from "react";
import Post from "../ui/order-list"; // Update import path

interface Order {
  id: string;
  title: string;
  content: string;
  authorName: string;
}

export default function Page() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchOrders() {
      try {
        const response = await fetch("/api/order/route"); // Fetch orders from the API endpoint
        if (!response.ok) {
          throw new Error("Failed to fetch orders");
        }
        const data = await response.json();
        setOrders(data.orders); // Set orders fetched from the API
        setLoading(false); // Set loading state to false after fetching data
      } catch (error) {
        console.error("Error fetching orders:", error);
        setError("Failed to fetch orders. Please try again later."); // Set error state if fetching fails
        setLoading(false); // Set loading state to false after fetching data
      }
    }

    fetchOrders(); // Call the function to fetch orders when component mounts
  }, []);

  // Display loading message while fetching data
  if (loading) {
    return <div>Loading...</div>;
  }

  // Display error message if fetching orders fails
  if (error) {
    return <div>{error}</div>;
  }

  return (
    <div className="container mx-auto mt-8 px-4 sm:px-0 text-gray-600">
      <h1 className="text-2xl font-bold text-gray-900 mb-4">Your Orders</h1>
      {/* Display message if no orders found */}
      {orders.length === 0 ? (
        <div>No orders found.</div>
      ) : (
        // Display orders if available
        <div className="flex flex-wrap">
          {orders.map((order) => (
            <Post
              key={order.id}
              id={order.id}
              title={order.title}
              content={order.content}
              authorName={order.authorName || "Unknown"}
            />
          ))}
        </div>
      )}
    </div>
  );
}

但是,我在部署时遇到此错误:

   ▲ Next.js 14.0.4
   - Environments: .env
   Creating an optimized production build ...
 ✓ Compiled successfully
   Linting and checking validity of types ...
Failed to compile.
src/app/api/orders/route.ts
Type error: Route "src/app/api/orders/route.ts" does not match the required types of a Next.js Route.
  "default" is not a valid Route export field.
Error: Command "npx prisma generate && next build" exited with 1

或查看此图片 https://github.com/vercel/next.js/assets/120279764/e6112b7f-a9d1-410e-b8f1-ac7ceced4695

这是我的 src/app/api/auth/[...nextauth]/route.ts

import { PrismaClient } from "@prisma/client";
import NextAuth, { User as NextAuthUser } from "next-auth";
import GoogleProvider from "next-auth/providers/google";

interface MyUser extends NextAuthUser {
  email: string;
  name?: string;
  // Add other user-related fields as needed
}

const prisma = new PrismaClient();

const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
  ],
  
  callbacks: {
    async signIn(params) {
      const { user } = params as { user: MyUser };

      try {
        const existingUser = await prisma.user.findUnique({
          where: { email: user.email },
        });

        if (!existingUser) {
          // If the user is not in the database, create a new user entry
          await prisma.user.create({
            data: {
              email: user.email,
              name: user.name || "", // Ensure 'name' is a string, even if it's undefined
              // Add other user-related fields as needed
            },
          });
        }

        return true; // Continue the sign-in process
      } catch (error) {
        console.error("Error during sign-in:", error);
        return false; // Stop the sign-in process if an error occurs
      }
    },
  },
});

export { handler as GET, handler as POST };

请帮忙。我不明白问题所在或解决方法是什么。我是 Nextjs 和 typescript 的新手。

我希望显示登录用户下的订单列表。

typescript next.js prisma vercel
1个回答
0
投票

我认为语法错误:

export default async function (req: NextApiRequest, res: NextApiResponse) {}

试试这个:

export const GET = (req: NextRequest, res: NextResponse) => {};
© www.soinside.com 2019 - 2024. All rights reserved.