How can I make http call to DialogFlow V2 using simple ajax jQuery?

一曲冷凌霜 提交于 2019-12-10 00:30:27

问题


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

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

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

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.

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

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?

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!

Edit: 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'
                    ]
                }
            }
        ],
    }

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

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...


回答1:


First of all, Dialogflow V1 API is not going away anytime soon. They do not have a definitive time line to stop the API. In case, they have decided, the developers will be notified with the deadline (confirmed by their support team). I guess you should be ok to use till then.

However, if you have decided 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.

Setup Instructions:

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.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.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});
    }
});


来源:https://stackoverflow.com/questions/50633291/how-can-i-make-http-call-to-dialogflow-v2-using-simple-ajax-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!