javascript - TypeError:无法读取未定义谷歌助手的属性“json”
问题描述
我正在使用 node.js 中的巴士站谷歌助手脚本,我基于谷歌的天气 API 示例。给定正确的 API 密钥,天气函数将工作并返回某个日期的某个地点的天气。
Bus Stop API 将在 console.log 中返回正确的输出,但输出不会传递到else if
调用函数的语句。
我收到 2 个错误:
"Unhandled rejection"
这可以通过注释掉 callBusApi 中的拒绝代码来缓解。"TypeError: Cannot read property 'json' of undefined at callBusApi.then.catch (/user_code/index.js:45:9) at process._tickDomainCallback (internal/process/next_tick.js:135:7)"
这就是它崩溃的地方。我认为是因为它没有从函数中获得输出。
我的脚本如下所示:
'use strict';
const http = require('http');
const host = 'api.worldweatheronline.com';
const wwoApiKey = 'enter a working key';
exports.weatherWebhook = (req, res, re) => {
if(req.body.queryResult.intent['displayName'] == 'weather'){
// Get the city and date from the request
let city = req.body.queryResult.parameters['geo-city']; // city is a required param
// Get the date for the weather forecast (if present)
let date = '';
if (req.body.queryResult.parameters['date']) {
date = req.body.queryResult.parameters['date'];
console.log('Date: ' + date);
}
// Call the weather API
callWeatherApi(city, date).then((output) => {
res.json({ 'fulfillmentText': output }); // Return the results of the weather API to Dialogflow
}).catch(() => {
res.json({ 'fulfillmentText': `I don't know the weather but I hope it's good!` });
});
}
else if (req.body.queryResult.intent['displayName'] == 'mytestintent'){
callBusApi().then((output) => {
re.json({ 'fulfillmentText': output }); // Return the results of the bus stop API to Dialogflow
}).catch(() => {
re.json({ 'fulfillmentText': `I do not know when the bus goes.` });
});
}
};
function callBusApi () {
return new Promise((resolve, reject) => {
http.get({host: 'v0.ovapi.nl', path: '/stopareacode/beunav/departures/'}, (re) => {
let boy = '';
re.on('data', (d) => {boy+=d});
re.on('end',() => {
let response = JSON.parse(boy)
var firstKey = Object.keys(response['beunav']['61120250']['Passes'])[0];
var timeKey = Object.keys(response['beunav']['61120250']['Passes'][firstKey])[19];
var destKey = Object.keys(response['beunav']['61120250']['Passes'][firstKey])[1];
let destination = response['beunav']['61120250']['Passes'][firstKey][destKey];
let datetime = response['beunav']['61120250']['Passes'][firstKey][timeKey];
let fields = datetime.split('T');
let time = fields[1];
let output = `Next bus to ${destination} departs at ${time} .`;
console.log(output)
resolve(output);
});
re.on('error', (error) => {
console.log(`Error talking to the busstop: ${error}`)
reject();
});
});
});
};
function callWeatherApi (city, date) {
return new Promise((resolve, reject) => {
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);
http.get({host: host, path: path}, (res) => {
let body = '';
res.on('data', (d) => { body += d; });
res.on('end', () => {
let response = JSON.parse(body);
let forecast = response['data']['weather'][0];
let location = response['data']['request'][0];
let conditions = response['data']['current_condition'][0];
let currentConditions = conditions['weatherDesc'][0]['value'];
let output = `Current conditions in the ${location['type']}
${location['query']} are ${currentConditions} with a projected high of
${forecast['maxtempC']}°C or ${forecast['maxtempF']}°F and a low of
${forecast['mintempC']}°C or ${forecast['mintempF']}°F on
${forecast['date']}.`;
console.log(output);
resolve(output);
});
res.on('error', (error) => {
console.log(`Error calling the weather API: ${error}`)
reject();
});
});
});
}
解决方案
看来你的方法参数太多了
exports.weatherWebhook = (req, res, re) => {
应该:
exports.weatherWebhook = (req, res) => {
以及用于处理 webhook 内的 'mytestintent' 的变量 're'。
这解释了尝试在其上设置 json 值时出现的“未定义”错误。
推荐阅读
- java - 如何从列表中的 LocalDate 获取 Java 中每个月的所有日期
- django - 如何创建动态 RAW 查询集
- youtube - Youtube api 获取子频道
- javascript - 如何忽略包中的 src 文件夹
- python - 调用密码检查器的函数
- prestashop - 在 smarty 多行上显示每个结果
- micronaut - 使用 Micronaut 创建返回二进制内容的 AWS Lambda 函数
- java - SpringBoot 2.0.2.RELEASE 中的 BCryptPasswordEncoder 定义
- jakarta-ee - 在 WebLogic 12c 上重新部署期间“JNDI 已在使用”
- git - 如何在 GitHub Web 界面中设置选项卡大小