为什么在应用程序目录内对 NextJS API 路由的请求会返回 500 响应代码?

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

Why the request to NextJS api route inside app directory gives 500 response code?

问题

When I try to call my API route I receive a 500 code Internal Server Error

Place of making the request:

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

    return data
}

Place of calling the fetcher:

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

Api route itself:

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
    })
}

File structure:
app > api > getSuggestion > route.ts
lib > fetchSuggestion.ts

I tried to change the app/api folder with pages/api like in the previous version of Next, but it didn't work. I checked if everything inside the route is okay, and it is, but I don't really understand why it gives me a 500 code.

英文:

When I try to call my API route I receive a 500 code Internal Server Error

Place of making the request

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

    return data
}

Place of calling the fetcher

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

Api route itself

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
    })
}

File sctructure

app>api>getSuggestion>route.ts

lib>fetchSuggestion.ts

I tried to change the app/api folder with pages/api like in previous version of Next, but it didn't work, checked if all inside the route is ok, and it is, but I don't really understand why it gives me 500 code.

答案1

得分: 1

最可能是你的获取逻辑出错了:

```typescript
export async function GET(request: Request) {
  try {
    // 连接到 mcrft azure func 端点
    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("get 路由内部错误", error);
    if (error instanceof Error) {
      return new Response(error.message, { status: 500 });
    }

    return new Response("内部服务器错误", { status: 500 });
  }
}

<details>
<summary>英文:</summary>

most likely your fetching logic is failing:

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

you should write the logic inside `try/catch` block

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



</details>



huangapple
  • 本文由 发表于 2023年5月15日 00:04:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76248449.html
匿名

发表评论

匿名网友

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

确定