【问题标题】:Send Request body to a google sheet using sheets API and XMLHttpRequest使用工作表 API 和 XMLHttpRequest 将请求正文发送到谷歌工作表
【发布时间】:2019-12-11 08:30:38
【问题描述】:

对于上下文,我正在 Qt QML 中做一个小型应用程序,需要将数据读/写到谷歌表中。阅读部分工作正常,但是我在使用 google sheet API V4 中的“sheets.spreadsheets.values.append”函数时遇到了问题(文档可以在这里找到:https://developers.google.com/sheets/api/reference/rest/

下面的Javascript函数将这个URL作为参数:https://sheets.googleapis.com/v4/spreadsheets/{SHEET-ID}/values/A2:ZZ:append?valueInputOption=RAW&key={API-KEY}

作为参数传递的请求体是这个:

{
 "majorDimension": "ROWS",
 "values": [
  [
   "15:41 02/08/2019",
   "Steven",
   "20",
   "Male",
   "test@mail.com",
   "FooBar"
  ]
 ]
}

执行 POST 调用的函数:

function postReq(url, callback, request = null) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url);
    xhr.onload = function (e) {
        if (e) console.log(e);
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                console.log(xhr.responseText);
                callback(xhr.responseText.toString());
            } else {
                callback(null);
                console.log(xhr.status);
            }
        } else {
            console.log(xhr.status);
        };
    };
    xhr.send(request);
};

这总是会返回一个 401 响应代码,即使我将工作表发布到网络上并且 API 密钥也不应该是问题,因为它在读取数据时工作正常(我确保工作表也是可编辑的)。

【问题讨论】:

    标签: javascript qt xmlhttprequest qml google-sheets-api


    【解决方案1】:
    • 您想使用 Sheets API 的 values.append 方法追加行。
    • 您正在为此使用 API 密钥。
    • Sheets API 已在 API 控制台中启用。

    如果我的理解是正确的,那么这个修改呢?请认为这只是几个答案之一。

    修改点:

    • 很遗憾,API 密钥不能用于 POST 方法。 API 密钥只能用于 GET 方法。所以请使用 OAuth2 和 Service account 检索到的 access token。
    • 对于您的脚本,请将请求正文作为内容类型的application/json 发送。

    修改脚本:

    作为使用访问令牌的脚本,我将您的脚本修改如下。在您使用它之前,请设置您的访问令牌。

    function postReq(url, callback, request = null) {
        const accessToken = "###"; // <--- Please set your access token here.
    
        // Sample request body?
        var request = {
         "majorDimension": "ROWS",
         "values": [
          [
           "15:41 02/08/2019",
           "Steven",
           "20",
           "Male",
           "test@mail.com",
           "FooBar"
          ]
         ]
        };
    
        var xhr = new XMLHttpRequest();
        xhr.open("POST", url);
        xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken); // Added
        xhr.setRequestHeader('Content-Type', 'application/json'); // Added
        xhr.onload = function (e) {
            if (e) console.log(e);
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    console.log(xhr.responseText);
                    callback(xhr.responseText.toString());
                } else {
                    callback(null);
                    console.log(xhr.status);
                }
            } else {
                console.log(xhr.status);
            };
        };
        xhr.send(JSON.stringify(request)); // Modified
    };
    

    注意:

    • 以上修改的脚本,在我的环境中,我可以确认它有效。

    参考资料:

    如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

    【讨论】:

    • 您很好地理解了我的问题,非常感谢您花时间在此回复中。不幸的是,在使用 OAuth2 时我有点迷茫,因为我以前从未使用过它,我希望 API 密钥能够工作,因为它更简单。无论哪种方式,我都非常感谢您的回复,您非常有帮助
    【解决方案2】:

    我们有类似的要求

    need to display the contents of a google sheet (rows & columns) on a html page (not using google web app), and sadly data not being displayed as a html page??
    
    the code loads the google sheet files, but no content is displayed???
    
    We have used code from following URL:
        https://www.w3schools.com/xml/xml_http.asp
    
    note:
    a/ have made public and publish the google sheet contents
    a.1/ using google drive, obtain following link:
    
    https://docs.google.com/spreadsheets/d/1HVmBfKjQiUyXOfy-q5iWVvDYOSKnMLPiDr18W2EtU9s/edit?usp=sharing
    
    a.2/ publish google sheet to the web
    
    https://docs.google.com/spreadsheets/d/e/2PACX-1vQ3ZHpAYDBhjSelXk-GFuFJACQzsqlufZ0d5UCLw8iJNJwdHglY7388fYHL4632wgXDIfgnrd238Htg/pubhtml
    
        <!DOCTYPE html>
    <html>
    <body>
    
    <h2>Using the amstras XMLHttpRequest Object</h2>
    
    <div id="demo">
    <button type="button" onclick="loadXMLDoc()">Load Data</button>
    </div>
    
    <script>
    function loadXMLDoc() {
      var xhttp = new XMLHttpRequest();
      var vUrl = "https://docs.google.com/spreadsheets/d/e/2PACX-1vQ3ZHpAYDBhjSelXk-GFuFJACQzsqlufZ0d5UCLw8iJNJwdHglY7388fYHL4632wgXDIfgnrd238Htg/pubhtml?gid=0&single=true&output=csv";
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("demo").innerHTML =
          this.responseText;
        }
      };
      xhttp.open("GET", vUrl , true);
      xhttp.send();
    }
    </script>
    
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2017-07-06
      • 2022-10-18
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多