Nextjs 天气应用程序尝试调用 api。不确定我做错了什么。我收到未经授权的错误

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

我的 api 处理正确吗?或者我缺少什么?这最初是一个 create React 应用程序项目,现在我正在尝试迁移到 nextjs,所以也许我错过了 api 调用应该如何完成的一些内容。如果我需要展示更多代码,请告诉我。

这是与主程序分开的。

export default async function ApiHandler(location) {
  
  try{
       

    const data = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${location}&units=imperial&appid=${process.env.API_KEY}`
      );
  
    const res = await data.json();

    
    console.log(res.data);
    
      } catch (error){
          console.log("Error connecting to api");
          return new Response("Error in getting weather data", { status: 500 });
      }

}
reactjs next.js async-await fetch-api openweathermap
1个回答
0
投票

在 NextJs 中,您需要在环境变量上使用 NEXT_PUBLIC_ 前缀,以便它们在客户端组件中公开(假设您在这里使用客户端组件)

请参阅文档:

https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser

© www.soinside.com 2019 - 2024. All rights reserved.