javascript - 使用 One Drive API 的错误 JSON 请求

标签 javascript jquery json api onedrive

我的目标是在我正在构建的应用程序中使用 Javascript/Jquery 在 OneDrive API 中以编程方式创建一个文件夹。我没有使用 Node.js 或 Angular.js。我已经在 OneDrive 的应用程序注册门户中注册了我的应用程序,然后使用 token 流从我的 Web 浏览器 url 地址栏中获取访问 token 。现在我有了访问 token ,我正在尝试将它和我的请求发送到 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"
 }
}

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

最佳答案

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

fetch这样的http库有很多, request - 这可以让你的生活更轻松

关于javascript - 使用 One Drive API 的错误 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50749437/

相关文章:

javascript - 如何使用 SweetAlert 进行 AJAX 调用

javascript - 搜索 JSON 对象并返回从给定键 :value? 向上一级的键

asp.net - JSON 中的 .d 是什么意思?

javascript - 已回答 : SyntaxError: JSON. 解析:预期为 ':' 但它位于对象的末尾

javascript - JavaScript 中用于 json post 的条件对象

javascript - 设置 highchart 中 y 轴的 double 最小值和最大值

jquery - mCustomScrollbar 不起作用(垂直滚动),我的列鼠标滚轮非常非常慢

jQuery 可排序

javascript - 如何在 react-js 中将 js 对象的值共享给 sass 变量?

javascript - 如何向本地存储 HTML5 添加多个文本