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



我的目标是在我正在构建的应用程序中使用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集成到应用程序中。

您正在发送对象,但内容类型为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库,如fetch,request - 可以让你的生活更轻松

相关内容

最新更新