创建 OneDrive 文件夹时如何修复 BadRequest 错误 "Unable to read JSON request payload"?

How do I fix BadRequest error "Unable to read JSON request payload" when creating a OneDrive folder?

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

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

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

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.
    }
}

您的代码有一个基本问题:您没有发布有效的 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"}'

,更有用:)