如何用Node.js的https.request加载天气API/JSON数据?
解决Node.js中https.request的getaddrinfo ENOTFOUND错误
嘿,我一眼就看到问题出在哪啦!你遇到的getaddrinfo ENOTFOUND https://api.weather.gov/stations/ https://api.weather.gov/stations/:80错误,完全是因为https.request的配置选项写错了,咱们来一步步修正:
错误原因分析
你的options配置有两个关键问题:
- hostname字段格式错误:
hostname只需要填写域名部分(比如api.weather.gov),不能带https://前缀和结尾的斜杠,否则Node.js会把整个字符串当成域名去解析,自然找不到对应的地址。 - port配置错误:HTTPS协议的默认端口是443,而你填了80(这是HTTP协议的默认端口),端口不匹配也会导致连接失败。
另外还有个小细节:path字段需要以/开头,确保和域名正确拼接。
修正后的完整代码
getTextWeatherUsingStationUsingRequest: function(theStation){ const https = require("https"); const thePath = `/stations/${theStation}/observations/current`; // 开头添加/ function requestTheData(){ var options = { hostname: "api.weather.gov", // 只保留域名 path: thePath, method: "GET", // 注意:api.weather.gov要求必须携带User-Agent请求头,否则会返回403 headers: { 'User-Agent': '你的应用名称/1.0 (你的联系邮箱)' } // HTTPS默认端口是443,不需要手动指定port字段,除非你用了非标准端口 }; var instaRequest = https.request(options); instaRequest.on("response", function(res){ console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.'); }); console.log("response"); console.log(res.statusCode); console.log(res.statusMessage); }); instaRequest.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); instaRequest.end(); } requestTheData(); }
额外注意事项
api.weather.gov的API有请求限制,要求必须在请求头里携带User-Agent(包含你的应用信息和联系方式),否则会返回403 Forbidden错误,所以我在代码里加上了这个配置,记得替换成你自己的信息哦。
内容的提问来源于stack exchange,提问作者Earth 2 Eddie
相关产品推荐
相关产品推荐

