Nodejs通过get请求获取api.open-meteo.com网站的天气数据
Nodejs通过get请求获取api.open-meteo.com网站的天气数据
继上一篇C++中使用cpp-httplib和nlohmann_json库实现http请求获取天气数据,想到使用Node.js获取天气数据更为方便,于是通过Node.js实现了get和post请求获取天气数据。
通常在开发GET和POST请求获取服务器上的数据前,我们可以根据Postman 或者curl`工具模拟http请求,如下图所示使用Postman get请求获取天气数据:

以下是基于Node.js的示例代码,展示了如何使用http请求模块发送GET 和POST 请求获取天气数据,对应代码如下:
const http = require('http');
const { hostname } = require('os');// Function to make a GET request to a weather API
function getWeather() {const options = {hostname: 'api.open-meteo.com',port: 80,path: '/v1/forecast?latitude=37.8136&longitude=144.9631¤t_weather=true',method: 'GET'};const req = http.request(options, (res) => {let data = '';// Collect data chunksres.on('data', (chunk) => {data += chunk;});// Process the complete responseres.on('end', () => {console.log('GET Response:');console.log(JSON.parse(data));});});req.on('error', (error) => {console.error(`Error: ${error.message}`);});req.end();
}// Function to make a POST request to a weather API
function postWeather() {const postData = JSON.stringify({latitude: 37.8136,longitude: 144.9631,current_weather: true});const options = {hostname: 'api.open-meteo.com',port: 80,method: 'POST',headers: {'Content-Type': 'application/json','Content-Length': Buffer.byteLength(postData)}};const req = http.request(options, (res) => {let data = '';// Collect data chunksres.on('data', (chunk) => {data += chunk;});// Process the complete responseres.on('end', () => {console.log('POST Response:');console.log(JSON.parse(data));});});req.on('error', (error) => {console.error(`Error: ${error.message}`);});// Write data to request bodyreq.write(postData);req.end();
}// Call the functions
getWeather();
postWeather();
以下是基于 Node.js 的示例代码,展示了如何使用 http 模块发送 GET 和 POST 请求来获取天气数据:
说明
-
GET 请求:
- 使用
http.request方法发送 GET 请求。 options中的path包含查询参数(纬度、经度等)。- 响应数据通过
res.on('data')收集,并在res.on('end')中处理。
- 使用
-
POST 请求:
- 使用
http.request方法发送 POST 请求。 postData是一个 JSON 对象,包含请求体数据。- 设置
Content-Type和Content-Length头部以匹配 POST 数据。
- 使用
-
错误处理:
- 使用
req.on('error')捕获请求中的错误。
- 使用
-
天气 API:
- 示例中使用了
api.open-meteo.com的免费天气 API。
- 示例中使用了
运行代码
-
保存文件
将代码保存为getWeather.js。 -
运行脚本
在终端中运行:node getWeather.js -
输出结果
- GET 请求的天气数据会打印到控制台。
- POST 请求的响应数据也会打印到控制台。
示例输出
GET Response:
{latitude: 37.8,longitude: 144.9375,generationtime_ms: 0.07319450378417969,utc_offset_seconds: 0,timezone: 'GMT',timezone_abbreviation: 'GMT',elevation: 0,current_weather_units: {time: 'iso8601',interval: 'seconds',temperature: '°C',windspeed: 'km/h',winddirection: '°',is_day: '',weathercode: 'wmo code'},current_weather: {time: '2025-11-01T12:15',interval: 900,temperature: 19.3,windspeed: 39.3,winddirection: 284,is_day: 0,weathercode: 0}
}POST Response:
{ reason: 'Not Found', error: true }
注意事项
- 如果天气 API 不支持 POST 请求,POST 请求可能会返回错误(如上例)。
- 如果需要更高级的 HTTP 功能,建议使用
axios或node-fetch模块。
