node.js中函数调用后API的响应范围

Posted

技术标签:

【中文标题】node.js中函数调用后API的响应范围【英文标题】:Scope of Response of API after function call in node.js 【发布时间】:2021-10-29 19:17:02 【问题描述】:

发布 API 格式


    "first_name": "sakshi",
    "last_name":"agrawal",
    "username":"sakshiagrawallllllll",
    "is_active":"1"

来自 POST API 的响应 如果用户已经注册,那么这将是响应的格式。


    "code": 404,
    "message": "User Already In Database"

如果用户没有注册,那么这将是响应。


    "code": 200,
    "message": 
        "first_name": "sakshi",
        "last_name": "agrawal",
        "username": "sakshiagrawallllllll",
        "is_active": "1",
        "updated_at": "2021-08-31T06:37:24.536000Z",
        "created_at": "2021-08-31T06:37:24.536000Z",
        "_id": "612dce240e357825b00182d2"
    ,
    "count": "",
    "data": ""

index.js 代码

'use strict';

// Import the Dialogflow module from the Actions on Google client library.
const  dialogflow  = require('actions-on-google');
const functions = require('firebase-functions');
// Instantiate the Dialogflow client.
const app = dialogflow( debug: true );
const axios = require('axios');

global.username='';
global.firstname='';
global.lastname='';
global.sessionId=0;
global.flag=0;
global.code=[];
global.sid=[];
global.ques=[];
global.response='';
global.res='';
global.data='';
global.rs = '';
global.resp=[];
global.reply = '';

app.intent('Default Welcome Intent', (conv) => 
  conv.add("Welcome to Smart Evaluation world’s largest database of evaluations and interview questions. Are you a registered user ?");
  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));
    function welcome(agent) 
      const sessionVars = 
        'userLang': 'en',  // possibilites handled - 'en', 'hi'
        'words': [],
        'questions': [],
        'currentIndexPosition': 0,
        'score': 0,
      ;
      const sessionContext =  'name': KEY_SESSION, 'lifespanCount': 100000, 'parameters': sessionVars ;
      agent.setContext(sessionContext);
      let sessionId = agent.session;
      conv.add(sessionId);
      sessionId=0;
    
    let intentMap = new Map();
    intentMap.set('Default Welcome Intent', welcome);
    agent.handleRequest(intentMap);
  );
);

app.intent('Non-Registered User', (conv) => 
  console.log(JSON.stringify(conv));
  var userreply = conv.body.queryResult.queryText;
  if (userreply == "no")
  
    conv.ask("In order to register you I will ask you a series of questions, please give honest feedback. Let’s begin. What is your first name? ");
    flag=0;
  
  else if (userreply == "yes")
  
    conv.ask("Welcome back, let’s get you authorized. What is your first name?");
  
);

app.intent('LastNameIntent', (conv) => 
  firstname = conv.parameters.any;
  conv.ask("What is your last name?" );
);

app.intent('UserNameIntent', (conv) => 
  lastname = conv.parameters.any;
  conv.ask("What is your user name?" );
);

app.intent('SecurityQuestionIntent', (conv) => 
  var reply;
  username = conv.parameters.any;
  conv.ask("Thank you" + firstname + lastname + username);
  if(flag == 0)
  
    async function makePostRequest() 
      var payload = 
        "first_name": firstname,
        "last_name": lastname,
        "username": username,
        "is_active": "1"
      ;
      console.log(payload);
      let res = await axios.post('API', payload, 
      headers:  'Content-Type' : 'application/json'
      )
       /*(error) => 
    console.log(error);
    );*/
    console.log("Response of data code is" + res.data.code);
    reply = res.data.code;
    console.log("Reply is " + reply);
    return reply;   
  
  reply = makePostRequest();
  console.log("Reply after method is" + reply);
  conv.ask(reply);
  
);

// Set the DialogflowApp object to handle theif() HTTPS POST request.
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);

package.json


  "name": "dialogflowFirebaseFulfillments",
  "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": 
    "node": "10"
  ,
  "scripts": 
    "start": "firebase serve --only functions:dialogflowFirebaseFulfillments",
    "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillments",
    "logs": "firebase functions:log"
  ,
  "dependencies": 
    "actions-on-google": "^2.4.0",
    "firebase-admin": "^5.13.1",
    "firebase-functions": "^2.0.2",
    "dialogflow": "^0.6.0",
    "dialogflow-fulfillment": "^0.6.0",
    "axios": "0.18.0",
    "aws-sdk": "2.696.0",
    "multivocal": "0.15.2",
    "express-session": "1.17.1"
  

当我尝试访问函数外部的“回复”变量时,如果尝试在函数内部打印,我会得到 [object Promise] 而打印效果很好。

如何在函数外部访问变量“回复”。有人可以帮我吗?

【问题讨论】:

twitter.com/@afirstenberg 请帮忙。 【参考方案1】:

这是异步函数的问题。它返回promise 对象(refrence):

异步函数总是返回一个承诺。如果异步函数的返回值不是显式的 Promise,它将被隐式包装在 Promise 中。

由于makePostRequest 是异步函数,因此需要使用一些异步构造(如thanawait)来获得结果。

我认为最简单的应该是更正reply 分配和流线到:

编辑:

return 声明添加到aviod Error: No rersponse has been sent

return makePostRequest().then(reply => 
  console.log("Reply after method is" + reply);
  conv.ask(reply);
)

【讨论】:

您好,感谢您的回复,我尝试这样做,但它没有打印在代码中,并且在控制台中运行良好。我附上了相同的屏幕截图。请检查并恢复。 @vitooh 好吧,它似乎正在工作:)。我认为您可以在makePostRequest 调用之前添加return 语句。你能测试并告诉我吗?我会更正答案。 感谢您的帮助。通过在语句中添加 return 确实有效。

以上是关于node.js中函数调用后API的响应范围的主要内容,如果未能解决你的问题,请参考以下文章

Node.js Lambda 函数从 REST 调用将“响应无效”返回给 Alexa 服务模拟器

无法通过递归调用node.js中的函数从promises获得响应

node.js 函数调用顺序,Spotify Web API

如何从 Node.js 中的 API 请求创建响应流?

在无状态 Node.js 应用程序中调度函数调用

Node JS在rest api响应中返回图像[关闭]