首页 > 解决方案 > 如何成功地将 dialogflow 与 node.js 集成

问题描述

我一直在学习关于如何为网站创建聊天机器人的 Udemy 课程。尝试向 Dialogflow 发送 POST 请求以确认集成是否成功时出现问题。这是我的代码:

 // Import the packages we need
const dialogflow = require('dialogflow', '@google-cloud/dialogflow');
//const dialogflow = require('@google-cloud/dialogflow');
require ('dotenv').config();
const config = require('../config/keys'); 
// create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(config.googleProjectID, config.dialogFlowSessionID);

module.exports = app => {
    app.get("/", (req, res) => {
        res.send({"hello": "Gerald"})
    });
    
    app.post("/api/df_text_query", async (req, res) => {
        const request = {
            session: sessionPath,
            queryInput: {
              text: {
                // The query to send to the dialogflow agent
                text: req.body.text,
                // The language used by the client (en-US)
                languageCode: config.dialogFlowSessionLanguageCode,
              },
            },
          }; 
          let responses = await sessionClient
          .detectIntent(request);

        res.send(responses[0].queryResult);
    });
    app.post("/api/df_event_query", (req, res) => {
        res.send({"do": "event query"})
    });
}

这是我使用邮递员发送 POST 请求时从 git bash 得到的错误

(node:7844) UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
 at GoogleAuth.getApplicationDefaultAsync (C:\Users\Gerald\Desktop\Chatbotdev\node_modules\google-auth-library\build\src\auth\googleauth.js:160:19)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async GoogleAuth.getClient (C:\Users\Gerald\Desktop\Chatbotdev\node_modules\google-auth-library\build\src\auth\googleauth.js:502:17)
    at async GrpcClient._getCredentials (C:\Users\Gerald\Desktop\Chatbotdev\node_modules\google-gax\build\src\grpc.js:92:24)
    at async GrpcClient.createStub (C:\Users\Gerald\Desktop\Chatbotdev\node_modules\google-gax\build\src\grpc.js:213:23)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7844) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7844) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

标签: node.jsdialogflow-es

解决方案


从日志中我可以看到您至少有 2 个问题。

第一个问题与Authentication.

(节点:7844)UnhandledPromiseRejectionWarning:错误:无法加载默认凭据。浏览到https://cloud.google.com/docs/authentication/getting-started了解更多信息。

此错误日志表明you didn't provide credentials with permissions要运行它。如错误中所述,您应该阅读有关身份验证入门的信息。要解决此问题,您应该使用以下方法之一创建服务帐户并按照Authenticating as a service account文档中的说明进行身份验证:

您可以在此线程中找到一些其他信息

第二个问题是缺乏catch ().

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 CLI 标志--unhandled-rejections=strict(请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。(拒绝编号:1)

堆栈上已经有一些类似的线程可以帮助您解决这个问题。正是在 IBM 博客 - Node.js 15 版本中提到了您的问题:更新了拒绝处理、npm 7、N-API 版本 7 等。下面这个博客中有趣的部分:

更新了拒绝处理

在以前的 Node.js 版本中,如果有未处理的拒绝,您会收到有关拒绝的警告和弃用警告。

  • 例如,以下示例:
new Promise((resolve, reject) => {
  reject('error');
});

将导致此弃用消息(与本例相同):

(node:31727) UnhandledPromiseRejectionWarning: error
(node:31727) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:31727) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
  • 您可以通过使用 catch 块处理拒绝来避免这些警告消息:
new Promise((resolve, reject) => {
  reject('error');
}).catch((error) => {});
  • 从 Node.js 15 开始,默认行为已更改为:
node:internal/process/promises:218
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "error".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

此外,您可以找到类似的 Stackoverflow 线程有类似的问题:

使用 JS async/await 处理那些未处理的承诺拒绝之类的指南


推荐阅读