Search code examples
reactjsgoogle-authenticationdialogflow-cx

How do I correctly add authorization to my Axios requests to Dialogflow CX API?


I want to communicate with the Dialogflow CX API from my React application. The relevant code looks like this:

componentWillMount() {
    let payload = {
        "queryInput": {
            "text": {
                "text": "Hi!"
            },
            "languageCode": "en"
        },
        "queryParams": {
            "timeZone": "America/Los_Angeles"
        }
    }
    axios.post('https://global-dialogflow.googleapis.com/v3/' + this.state.projectId + '/sessions/' + this.state.sessionId + ':detectIntent', payload)
        .then(response => {
            this.setState({ dialogResponse: response });
        })
        .catch(error => {
            console.log(error)
        })

    console.log(this.state.dialogResponse)
}

However, the response is 401.

I have create a service account and downloaded the private key as a JSON file as per https://cloud.google.com/docs/authentication/.

How do I then use this to authenticate my API call?


Solution

  • In the end, I couldn't get it to work by adding the JSON credentials to .env (did install dotenv). What I ended up doing:

    • Move the API call to my Express server

    • Add the JSON file to my project folder

    • Use the @google-cloud/dialogflow-cx library as follows:

       const { SessionsClient } = require('@google-cloud/dialogflow-cx');
       const client = new SessionsClient({
         keyFilename: "./my-file-name.json" //include the JSON file here!
       });
      
       ...
      
       app.get('/input', async (req, res, next) => {
         try {
           const sessionId = Math.random().toString(36).substring(7);
           const sessionPath = client.projectLocationAgentSessionPath(
             projectId,
             location,
             agentId,
             sessionId
           );
           console.info(sessionPath);
      
       const request = {
         session: sessionPath,
         queryInput: {
           text: {
             text: 'Hi there',
           },
           languageCode,
         },
       };
      
       const [response] = await client.detectIntent(request);
       for (const message of response.queryResult.responseMessages) {
         if (message.text) {
           console.log(`Agent Response: ${message.text.text}`);
         }
       }
       if (response.queryResult.match.intent) {
         console.log(
           `Matched Intent: ${response.queryResult.match.intent.displayName}`
         );
       }
       console.log(
         `Current Page: ${response.queryResult.currentPage.displayName}`
       );
      

      } catch (error) { return next(error) } })