What's the server-side equivalent of $.ajax() in Google Apps Scripts?

大憨熊 提交于 2019-12-09 06:54:47

问题


I want to perform an HTTP request from server-side code in a Google App Script with an Authorization header. Is there an App Script API for sending HTTP requests?

What's the equivalent of this code in a Google Apps Script?

 var api = "URL";
 $.ajax({
     type: 'GET',
     url: api,
     contentType: 'application/json',
     dataType:'json',
     data: {},
     beforeSend: function(xhr) {
         xhr.setRequestHeader('Authorization', makeBaseAuth('username', 'password'));
     }
});

回答1:


You can send HTTP requests using the UrlFetchApp object. It has a fetch(url, params) method that returns a HTTPResponse with information about the result of the HTTP fetch.

function testapi(){

    var encode =  Utilities.base64Encode('username:password', Utilities.Charset.UTF_8);
    Logger.log(encode);

    var option = {
      headers : {
            Authorization: "Basic "+ encode
      }   
    }

    var url = "URL";
    var response = UrlFetchApp.fetch(url, option).getContentText()
    response = JSON.parse(response);

    for (var key in response){
      Logger.log(key);
    }
}



回答2:


you need to use UrlFetchApp. see the official docs



来源:https://stackoverflow.com/questions/30378173/whats-the-server-side-equivalent-of-ajax-in-google-apps-scripts

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