How to successfully integrate dialogflow with node.js

Viewed 358

I have been following a course on Udemy on how to create a chatbot for websites. The problem arose when trying to send a POST request to Dialogflow to confirm if the integration was successful. 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

(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.
1 Answers

From Logs I can see that you have at least 2 issues.

First issue is related with Authentication.

(node:7844) UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.

This error log indicates that you didn't provide credentials with permissions to run this. 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 ().

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)

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. 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.

  • 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:
new Promise((resolve, reject) => {
  reject('error');
}).catch((error) => {});
  • As of Node.js 15, the default behavior has changed to :
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:

or guides like Handling those unhandled promise rejections with JS async/await

Related