SandeshR
SandeshR

Reputation: 213

Azure Bot Framework using React having issues

Below is my code is written for the bot framework,I refered the documentation in git hub and well as followed lots of article and a post from stack overflow, seems like it is throwing an error while displaying the bot at line WebChat.Chat, here is the link from the post in stackoverlfow as well :

declare var require: any
var React = require('react');
var ReactDOM = require('react-dom');
var DirectLine  = require('botframework-directlinejs');
//import * as WebChat from 'botframework-webchat';
var WebChat = require('botframework-webchat');


export class Hello extends React.Component {
    constructor() {
        super();
        this.state = { data: [] };
        this.variableValue = { dataValue: [] };

    }
    async componentDidMount() {
        const response = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer secretvalue',
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                accessLevel: 'View',
                allowSaveAs: 'false',
            })
        });
        // const { token } = await res.json();
        const { token } = await response.json();
        console.log(token);
        this.setState({ data: token });
        // 
    }
    render() {
        const {
            state: { data }
        } = this

        return (

            //<div>
            //    <p>Hello there1</p>
            //    <ul>
            //        {data}
            //    </ul>
            //</div>
            <WebChat.Chat
                directLine={{
                   data,
                    webSocket: false
                }}
                style={{
                    height: '100%',
                    width: '100%'
                }}
                //user={{
                //    id: 'default-user',
                //    name: 'Some User'
                //}}
            />



        );
    }

}

ReactDOM.render(<Hello />, document.getElementById('root'));

I am able to get the token via rest call but getting an error while having to display the bot, using WebChat.Chat directLine Below is the error: enter image description here enter image description here

EDIT I was able to run the code in the html file using react and babel,below is the code....

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>Web Chat: Integrate with React</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--
      For simplicity and code clarity, we are using Babel and React from unpkg.com.
    -->
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
    <!--
      For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
      or lock down on a specific version with the following format: "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
    <style>
      html, body { height: 100% }
      body { margin: 0 }

      #webchat {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="webchat" role="main"></div>
    <script type="text/babel">
        (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
        const headers = {"Authorization": "Bearer rngzqJ7rkng.cwA.A8k.xg_Jb-NbNs4Kq8O2CcF-vnNxy8nlCMPMPYaXL0oROr0"}
        const body = {"accessLevel": "View"}
        //const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST' }, {Headers:headers},{Body:body});
        //const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });

        const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
        method: 'POST',
        headers: {
        'Authorization': 'Bearer secretvalue',
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        },
        body: JSON.stringify({
        accessLevel: 'View',
        allowSaveAs: 'false',
        })
        });

        const { token } = await res.json();
        const { ReactWebChat } = window.WebChat;
        window.ReactDOM.render(
        <ReactWebChat directLine={ window.WebChat.createDirectLine({ token }) } />,
        document.getElementById('webchat')
        );

        document.querySelector('#webchat > *').focus();
        })().catch(err => console.error(err));
    </script>
  </body>
</html>

But when I am using it in a node js app, I am facing issues while using WebCHat.Chat.

Upvotes: 0

Views: 1215

Answers (1)

tdurnford
tdurnford

Reputation: 3712

There are two versions of Web Chat - v3 and v4. The StackOverflow issue you referenced is using Web Chat v3 while the dependency you are using is v4. Take a look at the code snippet below for how your Web Chat v4 implementation with Node should look.

import React from 'react';

import ReactWebChat, { createDirectLine } from 'botframework-webchat';

export default class extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      directLine: null
    };
  }

  componentDidMount() {
    this.fetchToken();
  }

  async fetchToken() {
    const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });
    const { token } = await res.json();

    this.setState(() => ({
      directLine: createDirectLine({ token })
    }));
  }

  render() {
    return (
      this.state.directLine ?
        <ReactWebChat
          className="chat"
          directLine={ this.state.directLine }
        />
      :
        <div>Connecting to bot&hellip;</div>
    );
  }
}

For more details, take a look at the samples on the GitHub Repo - sample 17 is a good example to look at for a Node implementation.

Upvotes: 3

Related Questions