dialogflow / dialogflow-nodejs-client

Node.js SDK for Dialogflow
Apache License 2.0
659 stars 287 forks source link

Api.ai Node.js Client-Server Application Tutorial #88

Open andreabazerla opened 7 years ago

andreabazerla commented 7 years ago

Hi, I'm a Node.js beginner and I don't know how to getting started with this Api.ai SDK for Node.js.

I just need a simple tutorial to create a basic Node.js client-server application, can you help me?

I've follow instructions on README.md and it works, but now I want to create a simple custom chat and then to deploy it on my remote server.

I've try to save main.js on my server, and with gulp-nodemon watch a second file that get user input; when it changes, server restarts but it doesn't work so well...

What npm/library I need to make my project? Can I get some little help to getting started? If you help me, I'll help you to contribute on documentation with my sample project and relative tutorial.

Thanks!

andreabazerla commented 7 years ago

Hi, now it works but through https Node.js module.

Is it right to use https instead main.js file in README.md?

I think it's wrong because my client access token is visible on client, but it works...

const https = require('https');

const clientAccessToken = '<MY CLIENT ACCESS TOKEN>';

const callback = (data) => {
  console.log(data);
  document.getElementById('answer').innerHTML = data.result.speech;
};

document.getElementById('submit').onclick = () => {
  const question = document.getElementById('question').value;

  const options =
  {
    hostname: 'api.api.ai',
    path: '/v1/query?lang=EN&query=' + encodeURIComponent(question) + '&sessionId=1',
    method: 'GET',
    headers: {
      Authorization: 'Bearer ' + clientAccessToken,
    },
  };

  https.get(options, (res) => {
    let body = '';
    res.on('data', (data) => {
      body += data;
    });
    res.on('end', () => {
      const result = JSON.parse(body);
      callback(result);
    });
  }).on('error', (e) => {
    console.log('Error: ' + e);
  });
};