我的 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 });
}
}
在 NextJs 中,您需要在环境变量上使用 NEXT_PUBLIC_ 前缀,以便它们在客户端组件中公开(假设您在这里使用客户端组件)
请参阅文档: