【问题标题】:TypeError: Cannot read property 'json' of undefined google assistantTypeError:无法读取未定义谷歌助手的属性“json”
【发布时间】:2018-07-30 09:18:37
【问题描述】:

我正在使用 node.js 中的 Bus Stop 谷歌助手脚本 我基于 Google 的天气 API 示例。给定正确的 API 密钥,天气函数将工作并返回某个日期的某个地点的天气。

Bus Stop API 将在 console.log 中返回正确的输出,但输出不会传递到调用函数的 else if 语句。

我收到 2 个错误:

  1. "Unhandled rejection" 可以通过注释掉 callBusApi 中的拒绝代码来缓解。
  2. "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();
      });
    });
  });
}

【问题讨论】:

  • 似乎re 对象未定义。你在哪里调用weatherWebhook() 函数? 3 个参数是否正确传递给该函数?
  • 你能把reoutput的值记录在callBusApi().then()里面吗?
  • 不,因为 .then 因为错误而永远不会执行。 weatherWebhook() 函数由 DialogFlow 调用。我知道re 必须以某种方式未定义,但为什么 callWeatherApi 有效而 callBusApi 无效?

标签: javascript node.js http-get actions-on-google google-assistant-sdk


【解决方案1】:

看来你的方法参数太多了

exports.weatherWebhook = (req, res, re) => {

应该是:

exports.weatherWebhook = (req, res) => {

还有用于处理 webhook 内的“mytestintent”的变量“re”。

这解释了尝试在其上设置 json 值时出现“未定义”错误。

【讨论】:

    【解决方案2】:

    关于你的2个问题:它通常是在没有定义变量的值时出现的。

    首先检查您是否在 .js 文件中定义了 JSON 变量。 或者其他格式。

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 2017-06-21
      • 2019-01-25
      • 2018-12-04
      • 1970-01-01
      相关资源
      最近更新 更多