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

本秂侑毒 提交于 2019-12-04 21:05:00
Raj Malakpet

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