Reputation: 23
I am creating a dialog in Google Sheets that generates and uploads a report to OneDrive. The user may need to create a folder in OneDrive through the dialog. However, when making the API request, I am getting a "BadRequest" error.
I have tried performing the request on the Windows command line using Curl. I have also tried using pure JS instead of the Google Script language. I am able to perform other actions such as searching OneDrive and uploading files.
// 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'}"
The Curl command produces the expected result, which is to create a new folder called "Test Folder" in our OneDrive root directory.
Both the GS and JS code above produce the following error message:
{
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.
}
}
Upvotes: 2
Views: 10005
Reputation: 22923
Your code has a basic problem: you don't poste valid JSON (even though your Header says so).
var reqBody = {
"name": "Test Folder",
"folder": {},
"@microsoft.graph.conflictBehavior": "rename"
};
This is just a normal javascript object. Doing a .toString()
on this would simply give you "[object Object]"
. You need to encode it to a USVString (basically a normal string), per the XHR docs. So to make it into something that the XHR#send()
method handles, do this:
var reqBody = JSON.stringify({
"name": "Test Folder",
"folder": {},
"@microsoft.graph.conflictBehavior": "rename"
});
The result is a string:
'{"name":"Test Folder","folder":{},"@microsoft.graph.conflictBehavior":"rename"}'
, which is far more usable :)
Upvotes: 3