我正在尝试使用 wit.ai快速入门示例。该示例适用于硬编码值,但是当我使用第三方天气 API 并尝试向用户提供响应时,它不起作用。
工作代码:
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
console.log('sending...', JSON.stringify(response));
},
getForecast({context, entities}) {
var location = firstEntityValue(entities, 'location');
if (location) {
context.forecast = 'sunny in ' + location; // we should call a weather API here
delete context.missingLocation;
} else {
context.missingLocation = true;
delete context.forecast;
}
return context;
},
};
现在我编写了函数 getWeather({ context,entities }, location) 来调用第三方天气 API 并获取用户给定位置的天气信息。
非工作代码:
var getWeather = function ({ context, entities }, location) {
console.log('Entities: ',entities)
var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + location + '&appid=myAppID';
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(typeof body)
var weatherObj = JSON.parse(body);
console.log('weather api res: ', weatherObj.weather[0].description);
context.forecast = weatherObj.weather[0].description + ' ' + location; // we should call a weather API here
delete context.missingLocation;
}
})
}
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
console.log('sending...', JSON.stringify(response));
},
getForecast({context, entities}) {
var location = firstEntityValue(entities, 'location');
if (location) {
//Call a function which calls the third party weather API and then handles the response message.
getWeather({ context, entities }, location);
} else {
context.missingLocation = true;
delete context.forecast;
}
return context;
},
};
另外,如果我稍微更改 getWeather() 函数并移动context.forecast = 'sunny in ' + location; 删除 context.missingLocation;在 request.get() 调用的回调函数之外,它将再次起作用,但此时我没有来自 3rd 方 api 的天气信息:
工作代码:
var getWeather = function ({ context, entities }, location) {
//Keeping context.forecast outside the request.get() callback function is useless as we yet to get the weather info from the API
context.forecast = 'sunny in ' + location;
delete context.missingLocation;
console.log('Entities: ',entities)
var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + location + '&appid=myAppID';
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(typeof body)
var weatherObj = JSON.parse(body);
console.log('weather api res: ', weatherObj.weather[0].description);
}
})
}
那么如何使context.forecast = apiRes + location; http调用回调中的线路工作?我在这里做错了什么?
注意: 我从 wit.ai 得到的错误响应:
错误:糟糕,我不知道该怎么办。
at F:\..\node-wit\lib\wit.js:87:15 at process._tickCallback (internal/process/next_tick.js:103:7)
我正在使用 npm 包请求在 Node.js中进行 http 调用。