如何使用 Javascript ajax 调用在 DialogFlow v2 上进行 http 调用 [英] How to make http call on DialogFlow v2 using Javascript ajax call

查看:28
本文介绍了如何使用 Javascript ajax 调用在 DialogFlow v2 上进行 http 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Node.js 的 DialogFlow 官方网站上找到了这个示例,它运行良好,但我不知道如何将其集成到我的 Web 应用程序中.

I found this example on the official site of DialogFlow using Node.js and it is working fine, but I dont know how do I integrate this into my web application.

是否可以将其集成到我的其他 javascript jquery 代码中?在这里我需要运行 node index.js 但如果我与我的代码集成,我还需要这样做吗?

Is it possible that I can integrate this into my other javascript jquery code? and here I need to run node index.js but do I still need to do this if I integrate with my code?

const projectId = 'xxx'; //https://dialogflow.com/docs/agents#settings
const sessionId = 'xxxxx';
const query = 'Hello';
const languageCode = 'en-US';

// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient();

// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
console.log(sessionPath);
// The text query request.
const request = {
  session: sessionPath,
  queryInput: {
    text: {
      text: query,
      languageCode: languageCode,
    },
  },
};

// Send request and log result
sessionClient
  .detectIntent(request)
  .then(responses => {
    console.log('Detected intent');
    const result = responses[0].queryResult;
    console.log(`  Query: ${result.queryText}`);
    console.log(`  Response: ${result.fulfillmentText}`);
    if (result.intent) {
      console.log(`  Intent: ${result.intent.displayName}`);
    } else {
      console.log(`  No intent matched.`);
    }
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

是否有任何替代方法可以让我们使用普通的 javascript jquery、ajax 来使用 DialogFlow v2,而无需每次我想使用 dialogflow 时都执行 node index.js.

Are there any alternative that we can use DialogFlow v2 using normal javascript jquery, ajax without me having to do node index.js everytime I want to use dialogflow.

DialogFlow v1 使用起来非常简单.我有这样的事情:

DialogFlow v1 was quite simple to use. I had it something like this:

fetch(url, {
    body: JSON.stringify(data),
    // cache: 'no-cache',
    // credentials: 'same-origin',
    headers: {
        'content-type': 'application/json',
        "Authorization": "Bearer " + configs.accessToken,
    },
    method: 'POST',
    mode: 'cors',
    redirect: 'follow',
    referrer: 'no-referrer',
})
    .then(response => response.json()) // parses response to JSON

推荐答案

正如其他人之前所说的,访问令牌的持续时间为一小时,过了这个时间就没有用了.因此,有必要对 API 进行一次调用(在我的情况下为 http 调用)以请求访问令牌,每小时一次,然后按照 Satheesh 的解释使用它.https://https://developers.google.com/identity/protocols/OAuth2ServiceAccount"developer.google.com/identity/protocols/OAuth2ServiceAccount.

As others have said here before, the access token has a duration of one hour, after that time it becomes useless. So it's necessary to make a call (http call in my case) to the API in order to request an access token, one time each hour, and use it as explained by Satheesh thereafter. Instructions on how to generate the signature to make the call and use it later are given in https://developers.google.com/identity/protocols/OAuth2ServiceAccount.

一旦您使用私钥和您必须使用的电子邮件(不是您的电子邮件,而是由服务帐户生成的电子邮件)从服务帐户中获取 json 文件,您就可以使用 jsrsasign 库(在纯 JavaScript 中),您可以在 https://github.com/kjur/jsrsasign 中找到,以生成 JSONWeb 签名 (JWS) 以及 JSON Web 令牌 (JWT),这是进行 http 调用以获取访问令牌所必需的.

Once you obtain the json file from the service account with the private key and the email you have to use (not your email, but the one generated by the service account), you can use the jsrsasign library (in pure javascript), that you can find in https://github.com/kjur/jsrsasign, to generate the JSON Web Signature (JWS) and thus the JSON Web Token (JWT), that will be needed to make the http call to get the access token.

然后您按照 Satheesh 上面的描述使用它通过 jQuery 调用 Dialogflow V2.

Then you use it as described above by Satheesh to make the call to Dialogflow V2 via jQuery.

我用来实现这一点的代码是下一个:

The code I have used to achieve this is the next one:

function _genJWS() {
    var header = '{"alg":"RS256","typ":"JWT"}';
    var claimSet = jwtClaimSet();
    var privateKey = jwtPrivateKey();

    var sHead = newline_toDos(header);
    var head = KJUR.jws.JWS.readSafeJSONString(sHead);
    var sPayload = newline_toDos(claimSet);
    var sPemPrvKey = privateKey;

    var jws = new KJUR.jws.JWS();
    var sResult = null;
    try {
        prv = KEYUTIL.getKey(sPemPrvKey);

        sResult = KJUR.jws.JWS.sign(head.alg, sHead, sPayload, prv);
    } catch (ex) {
        alert("Error: " + ex);
    }
    return sResult;
}

请求访问令牌:

function _requestAccessToken() {
    var access_token = accessToken;
    var assertion = _genJWS();
    console.log('Assertion: ' + assertion);
    jQuery.ajax({
        type: "POST",
        url: "https://www.googleapis.com/oauth2/v4/token",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        data: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + assertion,
        success: function(response) {
            console.log("success");
            console.log(response);
            access_token = response.access_token;
            console.log(access_token);
        },
        error: function() {
            console.log("Error");
        }
    });
    return access_token;
}

然后使用该访问令牌对 Dialogflow 进行 HTTP 调用.

Then use that access token to make the HTTP call to Dialogflow.

希望有帮助.

这篇关于如何使用 Javascript ajax 调用在 DialogFlow v2 上进行 http 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆