使用One Drive API

时间:2018-06-07 20:07:40

标签: javascript jquery json api onedrive

我的目标是在我正在构建的应用程序中使用Javascript / Jquery以编程方式在OneDrive API中创建文件夹。我没有使用Node.js或Angular.js。我已经在OneDrive的应用程序注册门户中注册了我的应用程序,然后使用令牌流从我的Web浏览器URL地址栏获取访问令牌。现在我有了访问令牌,我正在尝试将它和我的请求发送到API。以下是我的代码:

var accesshash = window.location.hash.substring(1);
    //console.log(url);
    console.log(accesshash);

    var token = JSON.parse('{' + accesshash.replace(/([^=]+)=([^&]+)&?/g, '"$1":"$2",').slice(0,-1) + '}', function(key, value) { return key === "" ? value : decodeURIComponent(value); });

    console.log(token.access_token);

    var url = "https://graph.microsoft.com/v1.0/me/drive/root/children/"
    var xhr = new XMLHttpRequest();

    if(xhr.readyState == 4) {
        console.log("success");
    }

    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.setRequestHeader("Authorization", "Bearer " + token.access_token);

    var newfolder = {
          "name": "0000000000",
          "folder": {}
        }
    xhr.send(newfolder);

我将此作为我的JSON响应:

{
  "error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.",
"innerError": {
  "request-id": "c8d43cbc-a59b-4244-8c4e-9193295ec7f8",
  "date": "2018-06-07T19:42:57"
 }
}

}

这是否意味着我的访问令牌至少有效?或者它有什么问题吗?有什么我想念的吗?这是我第一次尝试将Onedrive API集成到应用程序中。

1 个答案:

答案 0 :(得分:1)

您正在发送对象,但内容类型为application/json,json是javascript对象的字符串表示

xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); // added charset
xhr.setRequestHeader("Authorization", "Bearer " + token.access_token);

var newfolder = {
  "name": "0000000000",
  "folder": {}
}
xhr.send(JSON.stringify(newfolder)); // converted to string

有许多http库,如fetchrequest - 可以让您的生活更轻松