创建OneDrive文件夹时,如何解决BadRequest错误“无法读取JSON请求有效载荷”?

时间:2019-06-24 22:45:59

标签: javascript google-apps-script microsoft-graph onedrive

我正在Google表格中创建一个对话框,该对话框生成报告并将其上传到OneDrive。用户可能需要通过对话框在OneDrive中创建一个文件夹。但是,发出API请求时,出现“ BadRequest”错误。

我尝试使用Curl在Windows命令行上执行请求。我也尝试过使用纯JS而不是Google Script语言。我能够执行其他操作,例如搜索OneDrive和上传文件。

type objectContainingObjects = { [key: string]: object[] }

Curl命令产生预期的结果,该结果将在我们的OneDrive根目录中创建一个名为“测试文件夹”的新文件夹。

上面的GS和JS代码都产生以下错误消息:

// The GS code

var 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 code

function 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'}"

1 个答案:

答案 0 :(得分:1)

您的代码有一个基本问题:您不会发布有效的JSON(即使您的标头如此说)。

var reqBody = {
    "name": "Test Folder",
    "folder": {},
    "@microsoft.graph.conflictBehavior": "rename"
};

这只是一个普通的javascript对象。对此进行.toString()只会给您"[object Object]"。您需要将其编码为USVString(基本上是普通字符串)per the XHR docs。因此,要使其成为XHR#send()方法可以处理的内容,请执行以下操作:

var reqBody = JSON.stringify({
    "name": "Test Folder",
    "folder": {},
    "@microsoft.graph.conflictBehavior": "rename"
});

结果是一个字符串:

'{"name":"Test Folder","folder":{},"@microsoft.graph.conflictBehavior":"rename"}'

,它更加有用:)