TypeError: Cannot read property 'json' of undefined google assistant

TypeError: Cannot read property 'json' of undefined google assistant

我正在 node.js 中制作公交车站 google 助手脚本 我基于 Google 的天气 API 示例。给定正确的 API 键,天气功能将起作用,return 某个日期的天气。

Bus Stop API 将 return 在 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();
      });
    });
  });
}

关于你的第2个问题:它通常出现在变量的值未定义的时候。

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

看来你的方法参数太多了

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

应该是:

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

以及用于处理 webhook 中的 'mytestintent' 的变量 're'。

这解释了尝试设置 json 值时出现的 'not defined' 错误。