Google Fit聚合Rest API调用解析错误JavaScript

时间:2019-06-28 02:04:33

标签: javascript google-api google-fit google-fit-sdk

我正在按以下方式调用google fit rest api

 const requestBody ={
    "aggregateBy": [{
      "dataTypeName": "com.google.step_count.delta",
      "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
    }],
    "bucketByTime": { "durationMillis": 86400000 },
    "startTimeMillis": 1561228200000,
    "endTimeMillis": 1561652514300
    }

const userAction = async () => {
    const response = await fetch('https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate', {
      method: 'POST',
      body: requestBody, 
      headers: {
      'Content-Type': 'application/json',
      'Content-Length': '302',
      'Authorization': 'Bearer ' + authcode,
      }
    });
    const jsonResponse = await response.json();
    console.log(jsonResponse);
  }
  userAction();

我的回应是

{ "error": { "errors": [{ "domain": "global", "reason": "parseError", "message": "Parse Error" }], "code": 400, "message": "Parse Error" } }

不确定解析错误发生在哪里。任何帮助指出它发生的地方将不胜感激。 注意-身份验证令牌已正确获取,因此可能不是问题。 我也在本地主机上运行。

1 个答案:

答案 0 :(得分:0)

按照以下代码工作(我已经对静态参数进行了硬编码)。添加api密钥和客户端ID并运行即可。 此链接有帮助-https://github.com/jaysalvador/InputAccessoryView

<script>

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/fitness.activity.read"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("YOUR APP ID");
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/fitness/v1/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.fitness.users.dataset.aggregate({
      "userId": "me",
      "resource": {
        "aggregateBy": [
          {
            "dataTypeName": "com.google.step_count.delta",
            "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
          }
        ],
        "endTimeMillis": 1561652514300,
        "startTimeMillis": 1561228200000,
        "bucketByTime": {
          "durationMillis": 86400000
        }
      }
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "YOUR CLIENT ID"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>