由于“无法读取未定义的属性”添加”错误,功能不断崩溃

时间:2020-01-07 19:42:40

标签: javascript firebase dialogflow-es

运行此Firebase函数时,我不断收到此错误:

TypeError: Cannot read property 'add' of undefined
    at visaCountry (/srv/index.js:51:11)
    at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/srv/index.js:105:40)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:57:9)
    at /worker/worker.js:783:7
    at /worker/worker.js:766:11
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickDomainCallback (internal/process/next_tick.js:219:9)

agent变量在设置的范围内工作,但在undefined函数内部时返回visaCountry。有人知道为什么会这样吗?

功能

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

var serviceAccount = require("./config/sdkjfhdsjkhfjdsf.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://sdfdsfjshdfjds.firebaseio.com"
});

var db = admin.firestore();

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  console.log('Agent = '+ agent);

  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  // An action is a string used to identify what needs to be done in fulfillment
  let action = agent.action;
  console.log('Actions = '+ JSON.stringify(action));

  // Parameters are any entites that Dialogflow has extracted from the request.
  const parameters = agent.parameters; // https://dialogflow.com/docs/actions-and-parameters

  // Contexts are objects used to track and store conversation state
  const inputContexts = agent.contexts;

  function visaCountry(agent) {
    let visasRead = db.collection('requirements').doc('India').get();

    console.log('Agent = '+ agent);

    agent.add(`Here are the visas for` + visasRead.name);
  }
  let intentMap = new Map();
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('Visa Search Request', visaCountry());
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});

1 个答案:

答案 0 :(得分:1)

其背后的原因是因为您将函数定义为function visaCountry(agent) { }。从技术上讲,尝试从您未通过的函数作用域访问agent变量,这就是为什么它是undefined的原因。

只需将visaCountry()传递给变量agent

类似以下内容:

intentMap.set('Visa Search Request', visaCountry(agent));

想象一下:

const agent = 'data';

run();
run(agent);

function run(agent) {
  console.log(agent);
}

希望对您有帮助!