简体   繁体   English

如何将dialogflow与node.js成功集成

[英]How to successfully integrate dialogflow with node.js

I have been following a course on Udemy on how to create a chatbot for websites.我一直在关注关于如何为网站创建聊天机器人的 Udemy 课程。 The problem arose when trying to send a POST request to Dialogflow to confirm if the integration was successful.尝试向 Dialogflow 发送 POST 请求以确认集成是否成功时出现了问题。 Here is my code:这是我的代码:

 // 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"})
    });
}

Here is the error I get from git bash when I send a POST request using postman这是我使用 postman 发送 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.

From Logs I can see that you have at least 2 issues.从日志中我可以看到您至少有 2 个问题。

First issue is related with Authentication .第一个问题与Authentication有关。

(node:7844) UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. (节点:7844)UnhandledPromiseRejectionWarning:错误:无法加载默认凭据。 Browse to https://cloud.google.com/docs/authentication/getting-started for more information.浏览至https://cloud.google.com/docs/authentication/getting-started了解更多信息。

This error log indicates that you didn't provide credentials with permissions to run this.此错误日志表明you didn't provide credentials with permissions As mentioned in the error, you should read about Getting started with authentication .如错误中所述,您应该阅读身份验证入门 To solve this issue, you should create Service Account and authenticate as mentioned in Authenticating as a service account docs using one of below:要解决此问题,您应该使用以下方法之一创建服务帐户并按照身份验证为服务帐户文档中所述进行身份验证:

Some additional information you can find in this thread您可以在此线程中找到一些其他信息

Second issue is with lack of catch () .第二个问题是缺少catch ()

UnhandledPromiseRejectionWarning: Unhandled promise rejection. UnhandledPromiseRejectionWarning:未处理的 promise 拒绝。 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().此错误源于在没有 catch 块的情况下抛出异步 function,或者拒绝未使用 .catch() 处理的 promise。 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 ).要在未处理的 promise 拒绝时终止节点进程,请使用 CLI 标志--unhandled-rejections=strict (请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode )。 (rejection id: 1) (拒绝编号:1)

There are already a few similar threads on stack which should help you with solving this issue.堆栈上已经有一些类似的线程可以帮助您解决这个问题。 Exactly your issue was mentioned in IBM Blog - Node.js 15 release: Updated handling of rejections, npm 7, N-API Version 7, and more . IBM 博客 - Node.js 15 版本中确实提到了您的问题:更新了拒绝处理、npm 7、N-API 版本 7 等 Interesting part from this blog below:下面这个博客中有趣的部分:

Updated handling of rejections更新拒绝处理

In previous versions of Node.js, if there was an unhandled rejection, you would get a warning about the rejection and a deprecation warning.在 Node.js 的先前版本中,如果有未处理的拒绝,您将收到有关拒绝的警告和弃用警告。

  • For example, the following example:例如下面的例子:
new Promise((resolve, reject) => {
  reject('error');
});

would result in this deprecation message (same as in this case):将导致此弃用消息(与本例相同):

(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.
  • You can avoid these warning messaging by handling the rejection with a catch block:您可以通过使用 catch 块处理拒绝来避免这些警告消息:
new Promise((resolve, reject) => {
  reject('error');
}).catch((error) => {});
  • As of Node.js 15, the default behavior has changed to:自 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'
}

In addition, you can find similar Stackoverflow threads with similar issues:此外,您还可以找到具有类似问题的类似 Stackoverflow 线程:

or guides like Handling those unhandled promise rejections with JS async/await或像Handling those unhandled promise rejections with JS async/await这样的指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM