代码之家  ›  专栏  ›  技术社区  ›  Pickez

为什么在应用程序目录中对NextJS api路由的请求给出500响应代码?

  •  0
  • Pickez  · 技术社区  · 3 年前

    当我尝试调用我的API路由时,我收到一个500代码的内部服务器错误

    提出请求的地点

    export const fetchSuggestion = async () => {
        const response = await fetch('/api/getSuggestion', { cache: 'no-store' })
        const data = await response.json()
    
        return data
    }
    

    调用提取程序的位置

    const {
        data: suggestion,
        isLoading,
        isValidating,
        mutate,
      } = useSWR('/api/getSuggestion', fetchSuggestion, { revalidateOnFocus: false })
    

    Api路线本身

    export async function GET(request: Request) {
        // Connect to mcrft azure func endpoint
        const response = await fetch(`${process.env.VERCEL_URL || 'http://localhost:7071'}/api/getChatGPTSuggestion`, {
            cache: 'no-store'
        })
    
        const textData = await response.text()
    
        return new Response(JSON.stringify(textData.trim()), {
            status: 200
        })
    }
    

    文件结构

    应用程序>api>getSuggestion>路线.ts

    lib>fetchSuggestion.ts

    我试着像以前版本的Next一样,用pages/api更改app/api文件夹,但没有成功,检查了路由内的所有内容是否正常,确实如此,但我真的不明白为什么它会给我500个代码。

    1 回复  |  直到 3 年前
        1
  •  1
  •   Yilmaz    3 年前

    很可能您的获取逻辑失败了:

    const response = await fetch(`${process.env.VERCEL_URL || 'http://localhost:7071'}/api/getChatGPTSuggestion`, {
            cache: 'no-store'
        })
    

    你应该把逻辑写在里面 try/catch

    export async function GET(request: Request) {
      try {
        // Connect to mcrft azure func endpoint
        const response = await fetch(
          `${
            process.env.VERCEL_URL || "http://localhost:7071"
          }/api/getChatGPTSuggestion`,
          {
            cache: "no-store",
          }
        );
    
        const textData = await response.text();
    
        return new Response(JSON.stringify(textData.trim()), {
          status: 200,
        });
      } catch (error) {
        console.log("error inside get route",error)
        if (error instanceof Error) {
          return new Response(error.message, { status: 500 });
        }
    
        return new Response("Internal Server Error", { status: 500 });
      }
    }