jsonp ajax in google script

前端 未结 1 2044
我在风中等你
我在风中等你 2020-12-22 06:30

I\'m trying to learn how to query for data from a local government data site (hoping I can teach my math students to do some data analysis). I\'m hoping to get the data and

相关标签:
1条回答
  • 2020-12-22 06:46

    Issue:

    Whenever payload key is present in options/params argument of UrlFetchApp, the method is set to post by default. And any attempt to change the method to get is "silently" ignored. Other similar scripting platforms automatically convert the payload to url query parameters. But, UrlFetchApp silently changes the method to post and nothing else.

    Solution:

    Re-create the data object as a query string. For example, data:{x:1,y:2} should be changed to ?x=1&y=2 and appended to url.

    Snippet:

    function testapi() {
      var options = {
        method: 'get',
        // 'contentType': 'application/json',
        // 'payload' : data,//If set, method is ignored.
        headers: { Accept: '*/*', 'Content-Type': 'application/json' },
        muteHttpExceptions: true,
      };
    
      var url = 'https://data.gov.sg/api/action/datastore_search';
      //var url = 'https://httpbin.org/get'; test the method
    
      function objectToQueryParams(obj) {
        return (
          '?' +
          Object.entries(obj)
            .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
            .join('&')
        );
      }
      var data = {
        resource_id: '1b702208-44bf-4829-b620-4615ee19b57c', // the resource id
        limit: 5, // get 5 results
        q: 'Yishun', // query for 'Yishun'
      };
      var query = objectToQueryParams(data);
      url += query;
      var response = UrlFetchApp.fetch(url, options).getContentText();
      Logger.log(response);
    }
    

    function objectToQueryParams(obj) {
      return (
        '?' +
        Object.entries(obj)
          .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
          .join('&')
      );
    }
    
    
    var data = {
      resource_id: '1b702208-44bf-4829-b620-4615ee19b57c', // the resource id
      limit: 5, // get 5 results
      q: 'Yishun', // query for 'jones'
    };
    console.log(objectToQueryParams(data));

    Related:

    UrlSearchParams

    0 讨论(0)
提交回复
热议问题