首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用一个驱动器API的错误JSON请求

使用一个驱动器API的错误JSON请求
EN

Stack Overflow用户
提问于 2018-06-08 04:07:40
回答 1查看 257关注 0票数 0

我的目标是在构建的应用程序中使用Javascript/ OneDrive以编程方式在Jquery 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集成到应用程序中。

EN

回答 1

Stack Overflow用户

发布于 2018-06-08 04:15:13

您正在发送对象,但内容类型是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

有许多像fetchrequest这样的http库可以让你的工作更轻松。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50749437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档