未处理的拒绝:标头发送后无法设置 [英] Unhandled Rejection: Headers cant be set after they are sent

查看:56
本文介绍了未处理的拒绝:标头发送后无法设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a chatbot in Dialogflow. I am trying to add the data to the database when its throwing an error of Unhandled Rejection.

这是我的 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);
});

这是我收到的错误:

时在MyFunctionHandler中发生的错误,我在这里没有看到类似的问题,但是都没有他们得到了答复。谁能帮忙吗?我已经在这个问题上停留了一个多星期。

I have seen few similar questions here but none of them are answered. Can anyone please help? I have been stuck in this for over a week already.

推荐答案

问题是 yourFunctionHandler(代理)函数正在异步执行操作,但未返回Promise。相反,它什么也不返回,因此处理立即返回而没有发送消息。

The problem is that the yourFunctionHandler(agent) function is doing things asynchronously, but isn't returning a Promise. Instead, it returns nothing, so the processing returns immediately without having a message sent.

因为它看起来像是 myDoc.add()返回一个Promise,通过使返回myDoc.add(...)。then(...)等等很容易处理。可能看起来像这样:

Since it looks like myDoc.add() returns a Promise, this is easy to handle by making that return myDoc.add(...).then(...) and so forth. It might look something like this:

  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()为您创建响应。

Additionally, you're mixing handling the response yourself (by calling response.send()) and using the Dialogflow agent.handleRequest(), which will create a response for you.

您应该使用Dialogflow方法生成类似

You should either use the Dialogflow methods to generate the reply with something like

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

或自己使用JSON中的值来确定要使用类似的处理程序调用

or use the values in the JSON yourself to determine which handler to call with something like

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

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

(You may need to vary this. It looks like from your code you're using Dialogflow v1, which I've reflected, and the path for the intent name changes for v2. You also should check for the handler not existing, may want to send parameters, etc.)

这篇关于未处理的拒绝:标头发送后无法设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆