我正在 Google 表格中创建一个对话框,用于生成报告并将其上传到 OneDrive。用户可能需要通过对话框在 OneDrive 中创建一个文件夹。但是,在发出 API 请求时,出现“BadRequest”错误。我尝试使用 Curl 在 Windows 命令行上执行请求。我也尝试过使用纯 JS 而不是 Google Script 语言。我能够执行其他操作,例如搜索 OneDrive 和上传文件。// The GS codevar auth = "Bearer " + acc;var options = { "method": "post", "headers": { "Authorization": auth, "Content-Type": "application/json" }, "payload": { "name": "Test Folder", "folder": {}, "@name.conflictBehavior": "rename" }, "muteHttpExceptions": true};var reqUrl = "https://graph.microsoft.com/v1.0/me/drive/root/children";var response = UrlFetchApp.fetch(reqUrl, options);var json = JSON.parse(response);Logger.log(json); // The JS codefunction onAuthSuccess(acc) { var pNum = document.getElementById("projectnum").value; var pName = document.getElementById("address").value; var reqUrl = "https://graph.microsoft.com/v1.0/me/drive/root/children"; var reqBody = { "name": "Test Folder", "folder": {}, "@microsoft.graph.conflictBehavior": "rename" }; var auth = "Bearer " + acc; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { console.log(xhr.responseText); } xhr.open("POST", reqUrl, true); xhr.setRequestHeader("Authorization", auth); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(reqBody);}// The successful Curl command// curl "https://graph.microsoft.com/v1.0/me/drive/root/children" -X POST -H "Content-Type: application/json" -H %acc% -d "{'name':'Test Folder', 'folder':{}, '@microsoft.graph.conflictBehavior':'rename'}"Curl 命令产生了预期的结果,即在我们的 OneDrive 根目录中创建一个名为“Test Folder”的新文件夹。上面的 GS 和 JS 代码都会产生以下错误消息:{ error = { code = BadRequest, innerError = { date = 2019 - 06 - 24 T20: 40: 52, request - id = ##################### }, message = Unable to read JSON request payload.Please ensure Content - Type header is set and payload is of valid JSON format. }}
1 回答
杨魅力
TA贡献1811条经验 获得超6个赞
您的代码有一个基本问题:您没有发布有效的 JSON(即使您的 Header 是这样说的)。
var reqBody = {
"name": "Test Folder",
"folder": {},
"@microsoft.graph.conflictBehavior": "rename"
};
这只是一个普通的 javascript 对象。.toString()在这上面做一个只会给你"[object Object]"。根据 XHR 文档,您需要将其编码为 USVString(基本上是普通字符串)。因此,要使其成为该XHR#send()方法处理的内容,请执行以下操作:
var reqBody = JSON.stringify({
"name": "Test Folder",
"folder": {},
"@microsoft.graph.conflictBehavior": "rename"
});
结果是一个字符串:
'{"name":"Test Folder","folder":{},"@microsoft.graph.conflictBehavior":"rename"}'
,这更有用:)
添加回答
举报
0/150
提交
取消