首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >未处理的拒绝:发送后不能设置标头

未处理的拒绝:发送后不能设置标头
EN

Stack Overflow用户
提问于 2018-05-29 13:34:17
回答 1查看 1.6K关注 0票数 2

我在Dialogflow中创建了一个聊天机器人。当数据库抛出未处理的拒绝错误时,我试图将数据添加到数据库中。

这是我的index.js文件。

'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
//const {Card, Suggestion} = require('dialogflow-fulfillment');
var admin = require('firebase-admin');
//require("firebase/firestore");
admin.initializeApp(functions.config().firebase);
var firestore = admin.firestore();
//var db = firebase.firestore();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

var addRef = firestore.collection('Admission');
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
  console.log("request.body.queryResult.parameters: ", request.body.queryResult.parameters);
  let params = request.body.queryResult.parameters;


  /* function welcome (agent) {
    agent.add(`Welcome to my agent!`);
  } */

  /* function fallback (agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  } */

  let responseJson ={};

  function yourFunctionHandler(agent) {
    var docRef = firestore.collection('users');
    name = request.body.queryResult.parameters['myname'];
    coll = request.body.queryResult.parameters['college_name'];
    name = name.charAt(0).toUpperCase() + name.slice(1);
    let balanceresponse = {};
    console.log(name);
    return docRef.add({
      myname: name,
      college: coll
    })
    .then((querySnapshot)=>{
      balanceresponse = {
        "fulfillmentText": 'Sure '+name+', Do you want to know about Admissions, Fees, Graduates and PG, Contact information, Media or Testimonials?'

      }
      console.log('before response.send()');
      response.send(balanceresponse); 
     /*  console.log('before response.send()');
      response.send({
        fulfillmentText:  
             'Sure '+name+', Do you want to know about Admissions, Fees, Graduates and PG, Contact information, Media or Testimonials?'
        //response.json(responseJson);
        }); */
        console.log('after response.send()');
      return 1;
    })
    .catch(error => {
      response.send({
        fulfillmentText:  
          'Something went wrong with the database'
        });
    });
  }

  function AdmissionHandler(agent) {
      console.log("inside Admission Handler");
      let balanceresponse = {};
      let Question = request.body.queryResult.parameters['question'];
      addRef.where("Question", "==", Question)
      .get().then((querySnapshot)=>{
      if (querySnapshot) {
          console.log("Document data:");
          const tips = querySnapshot.docs;
          const tipIndex = Math.floor(Math.random() * tips.length);
          const tip = tips[0];
          balanceresponse = {
            "fulfillmentText": ' Anything else you wanna know?'

         }
         console.log('before response.send()');
         response.send(balanceresponse); 
          /*  response.send({
            fulfillmentText:  
            //firestore.collection(addRef.Answer)+ 
            ' Anything else you wanna know?'
          });  */
          return 1;
      } else {
          // doc.data() will be undefined in this case
          console.log("No such document!");
      }
    return 1;
    })
    .catch(function(error) {
      console.log("Error getting document:", error);
     });


  } 


  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
 // intentMap.set('Default Welcome Intent', welcome);
 // intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('GetName', yourFunctionHandler);
  intentMap.set('AdmissionCustom', AdmissionHandler);
  agent.handleRequest(intentMap);
});

这是我收到的错误:

我在这里看到了几个类似的问题,但没有一个得到回答。有人能帮帮忙吗?我已经被困在这里一个多星期了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-29 23:14:10

问题是yourFunctionHandler(agent)函数异步执行操作,但没有返回Promise。相反,它不返回任何内容,因此处理立即返回,而不发送消息。

因为它看起来像是myDoc.add()返回了一个Promise,所以这很容易通过生成return myDoc.add(...).then(...)等方法来处理。它可能看起来像这样:

  function yourFunctionHandler(agent) {
    return docRef.add({
      myname: name,
      college: coll
    })
    .then(()=>{
      response.send({
        fulfillmentText:  
          'Sure '+name+', Do you want to know about Admissions, Fees, Graduates and PG, Contact information, Media or Testimonials?'
      });
      return 1;
    })
    .catch(error => {
      //console.log('érror',e);
      response.send({
        fulfillmentText:  
          'Something went wrong with the database'
        });
    });
  }

此外,您可以自己处理响应(通过调用response.send())和使用Dialogflow agent.handleRequest(),这将为您创建响应。

您应该使用Dialogflow方法生成回复,如下所示

agent.add("No such document found.");

或者自己使用JSON中的值来确定要调用哪个处理程序,例如

const intentName = request.body.queryResult.intent.name;
const handler = intentMap[intentName];
handler();

(您可能需要对此进行更改。从您的代码看,您使用的是Dialogflow v1,我已经反映了这一点,并且v2的意图名称的路径发生了更改。您还应该检查处理程序是否不存在、可能想要发送参数等。)

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50576932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档