如何在TypeScript Firebase函数中提取API返回的气温值?
提取天气API返回的气温值
基础实现(快速满足需求)
直接访问返回数据里嵌套的current_weather.temperature属性即可,同时建议添加异常处理避免请求或数据解析失败导致的报错:
export const getWeather = functions.https.onRequest(async (request, response) => { try { const dataResponse = await fetch("https://api.open-meteo.com/v1/forecast?latitude=40.71&longitude=-74.01&hourly=temperature_2m¤t_weather=true"); const data = await dataResponse.json(); // 提取气温值,用可选链避免current_weather不存在时报错 const temperature = data.current_weather?.temperature; if (temperature === undefined) { response.status(400).send("无法获取气温数据"); return; } response.send({ temperature }); // 以对象形式返回,也可直接用response.send(temperature)返回纯数值 } catch (error) { response.status(500).send("请求天气API失败"); } });
TypeScript类型安全优化(推荐)
作为TypeScript项目,定义接口约束API返回结构能获得类型检查和代码补全,减少潜在bug:
// 定义API返回数据的类型接口 interface CurrentWeather { temperature: number; windspeed: number; winddirection: number; weathercode: number; time: string; } interface WeatherApiResponse { current_weather: CurrentWeather; } export const getWeather = functions.https.onRequest(async (request, response) => { try { const dataResponse = await fetch("https://api.open-meteo.com/v1/forecast?latitude=40.71&longitude=-74.01&hourly=temperature_2m¤t_weather=true"); if (!dataResponse.ok) { throw new Error(`API请求失败,状态码:${dataResponse.status}`); } const data = await dataResponse.json() as WeatherApiResponse; const temperature = data.current_weather.temperature; response.send({ temperature }); } catch (error) { console.error(error); response.status(500).send("获取天气数据失败"); } });
关键要点
- 可选链操作符
?.可以避免current_weather字段不存在时抛出运行时错误。 try-catch块能捕获网络请求、数据解析过程中的异常,保证函数稳定性。- TypeScript类型定义能让你在编码阶段发现类型不匹配问题,提升代码可靠性。
内容的提问来源于stack exchange,提问作者sopatd
相关产品推荐
相关产品推荐

