【发布时间】:2018-04-21 03:24:52
【问题描述】:
每次我提交下面的代码时,我都会收到此错误。我是 Node.js 的新手,我正在尝试通过简单的 api 交互来部署天气功能(本页中的示例 link)。
Error: getaddrinfo ENOTFOUND api.worldweatheronline.com
api.worldweatheronline.com:80
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
'use strict';
const http = require('http');
const host = 'api.worldweatheronline.com';
const wwoApiKey = 'here i write my api key';
exports.weatherWebhook = (req, res) => {
// Get the city and date from the request
let city = req.body.result.parameters['geo-city']; // city is a required param
// Get the date for the weather forecast (if present)
let date = '';
if (req.body.result.parameters['date']) {
date = req.body.result.parameters['date'];
console.log('Date: ' + date);
}
// Call the weather API
callWeatherApi(city, date).then((output) => {
// Return the results of the weather API to Dialogflow
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': output, 'displayText': output }));
}).catch((error) => {
// If there is an error let the user know
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': error, 'displayText': error }));
});
};
function callWeatherApi (city, date) {
return new Promise((resolve, reject) => {
// Create the path for the HTTP request to get the weather
let path = '/premium/v1/weather.ashx?format=json&num_of_days=1' +
'&q=' + encodeURIComponent(city) + '&key=' + wwoApiKey + '&date=' + date;
console.log('API Request: ' + host + path);
// Make the HTTP request to get the weather
http.get({host: host, path: path}, (res) => {
let body = ''; // var to store the response chunks
res.on('data', (d) => { body += d; }); // store each response chunk
res.on('end', () => {
// parsing and submit the response (not included in this code)
..
// Resolve the promise with the output text
console.log(output);
resolve(output);
});
res.on('error', (error) => {
reject(error);
});
});
});
}
我该如何解决?看来我的http请求是错误的。
【问题讨论】:
-
听起来好像服务器上的 DNS 解析不正确。域 api.worldweatheronline.com 确实存在。
-
你试过在机器上ping api.worldweatheronline.com吗?
Pinging api.worldweatheronline.com [31.193.9.233] with 32 bytes of data: Request timed out. Reply from 31.193.9.233: bytes=32 time=23ms TTL=52 Reply from 31.193.9.233: bytes=32 time=23ms TTL=52 Reply from 31.193.9.233: bytes=32 time=23ms TTL=52 Ping statistics for 31.193.9.233: Packets: Sent = 4, Received = 3, Lost = 1 (25% loss), Approximate round trip times in milli-seconds: Minimum = 23ms, Maximum = 23ms, Average = 23ms