如何使用简单的Ajax jQuery对DialogFlow V2进行http调用? [英] How can I make http call to DialogFlow V2 using simple ajax jQuery?

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

问题描述

在一直使用jQuery之前,我一直在使用DialogFlow v1,这是非常直接的工作!

I have been using DialogFlow v1 before using simply jquery and it was pretty straigh forward working!

现在我必须切换到V2,我被困在如何保持相同的代码,但是只是使用V2进行修改!

Now that I have to switch to V2 I am stuck on how to keep somehow same code but just modify with the V2!

我一直在寻找V2的此客户端库:
https://github.com/dialogflow/dialogflow-nodejs-client-v2#using-the -client-library

I have been looking at this client library for V2: https://github.com/dialogflow/dialogflow-nodejs-client-v2#using-the-client-library

但是我不想使用Node.js,我只是不想做像node server.js这样的事情来运行应用程序,我也我不确定是否可以将jQuery与Node.js混合使用。

But I dont wanna use Node.js I just dont want to do somthing like node server.js to run the app, also I am not sure if I can mix jQuery with Node.js.

我以前的代码v1看起来像这样:

My previous code v1 looked 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

的响应好了我转至ES6以发出http请求用于dialogflow,但我想将相同的代码用于V2,这可能吗?另外我再也看不到v2的访问令牌,我们应该如何处理http调用的auth?

Well I swtiched to ES6 for making http request for dialogflow but I would want the same code to use for V2, is this possible? Also I can no longer see access token for v2, how are we suppose to handle the auth for http calls?

我真的对新的V2感到困惑,因为我们切换到了企业版帐户,所以使用v2是我们必须使用的,而且有点烂!

I am really confused with the new V2 and since we switched to Enterprise Edition Account it is a must for us to use v2 and it kinda sucks!

编辑:
我正在从文档中检查此示例:

I am checking this example from documentation:

  POST https://dialogflow.googleapis.com/v2beta1/projects/project-name/agent/intents

    Headers:
    Authorization: Bearer $(gcloud auth print-access-token)
    Content-Type: application/json

    POST body:
    {
        'displayName': 'StartStopwatch',
        'priority': 500000,
        'mlEnabled': true,
        'trainingPhrases': [
            {
                'type': 'EXAMPLE',
                'parts': [
                    {
                        'text': 'start stopwatch'
                    }
                ]
            }
        ],
        'action': 'start',
        'messages': [
            {
                'text': {
                    'text': [
                        'Stopwatch started'
                    ]
                }
            }
        ],
    }

但是我对此部分感到困惑:授权:不记名$(gcloud auth print -access-token)从哪里获得访问令牌?

But I am somehow confused on this part: Authorization: Bearer $(gcloud auth print-access-token) where do I get access-token?

我已经完成了这一部分:gcloud auth activate-service-account --key-file =我不知道激活后它在做什么!我希望可以从中得到一些访问令牌,但是似乎没有什么消息只说已激活服务...。

I have already done this part: gcloud auth activate-service-account --key-file= which I have no idea what is it doing after activating! I was hoping I would get back some access-token from this, but there seem to be nothing just a message that says Activated Service...

推荐答案

要像V1一样将Dialogflow V2 API与浏览器AJAX一起使用,没有简单的方法,除非您具有访问令牌。我遇到了同样的问题,并且发现如果不使用其客户端库(SDK)或 google-oauth-jwt就无法解决此问题。在我的示例中,我使用了nodejs-google-oauth-jwt程序包,该程序包为用于浏览器AJAX调用的应用程序提供访问令牌。如果您在客户端处理逻辑,则不必使用他们的nodejs SDK库。

To use Dialogflow V2 API with browser AJAX just like V1, there is no simple way, unless you have the access token. I've run into same issue and figured out it can't be done without using their client libraries (SDK) or "google-oauth-jwt". In my example i used nodejs - google-oauth-jwt package which provides "access token" for my application which was used for browser AJAX calls. You don't have to use their nodejs SDK library, in case, you're handling logic on client side.

设置说明:

1。从dialogflow帐户的V1配置V2 API,请遵循迁移指南。下载具有唯一电子邮件和键值的JSON文件。您可能想要通过注册域来授予对应用程序的访问权限。

1.Configure V2 API from V1 on the dialogflow account, follow the migration guide. Download the JSON file which has a unique email and key values. You might want to grant access to your application by registering the domains.

2。创建一个nodejs应用程序,并使用 google-oauth-jwt获取访问令牌。同样,将此作为一项服务来进行调用,以便在进行任何ajax调用之前先准备好访问令牌。这是示例代码:

2.Create a nodejs application and use "google-oauth-jwt" to get the access token. Also, make this as a service to call it before hand to have the access token ready before making any ajax calls. Here is sample code:

app.get("/your_sample_web_service_to_get_access_token", (req, res, next) => {
new Promise((resolve) => {
    tokens.get({
            //find this email value from the downloaded json
            email: 'xxx@xxx.iam.gserviceaccount.com',
            //find this key value from the downloaded json
            key: '-----BEGIN PRIVATE KEY-----xxx',
            //specify the scopes you wish to access: as mentioned in dialogflow documentation
            scopes: ['https://www.googleapis.com/auth/cloud-platform']
        },
        (err, token) => {
            //rest api response
            res.json({
                "access_token": token
            });
            resolve(token);
        }
    );
});
});

3。使用客户端JavaScript,使用从上述nodejs应用程序获得的访问令牌进行AJAX调用。下面是示例代码:

3.From your client JavaScript, make an AJAX call using the access token you get from above nodejs application. Here is the sample code:

app.service('chatbot', function ($http, $rootScope) {
    this.callAPI = function (user_entered_query) {
        //I used detectintent REST API endpoint: find the project name from your account.
        var endpoint = "https://dialogflow.googleapis.com/v2/projects/xxx/agent/sessions/123456789:detectIntent";
        var data = JSON.stringify({queryParams:{}, query_input:{text:{text:user_entered_query,language_code:"en-US"}},outputAudioConfig:{},inputAudio:""});
        var headers = {
            //use the token from nodejs service
            "Authorization": "Bearer " +$rootScope.token
        };
        return $http.post(_url, _data, {"headers": headers});
    }
});

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

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