Reputation: 23
Basically I am trying to update a file on Github using the api. When I do this in Poster it works no problem and I get a response from the server. When sending the exact same params in an xhr put request however, I receive a 400: Bad request error - Problems parsing JSON. Heres my request:
var contentArgs = {
"message": "Auto TODO commit updating technical debt",
"committer": {
"name": "TODO",
"email": "[email protected]"
},
"content": "bXkgdXBkYXRlZCBmaWxlIGNvbnRlbnRz",
"sha": "fb617c9e42866ca2446545e0c2725048f6f9530c"
};
xhr.put({
// The URL to request
url : url,
headers : {"Authorization" : "token 289543b6aca2454165451a1afcf115fa9a97"},
content : contentArgs,
handleAs : "json",
load : lang.hitch(this,function(result) {
deferred.resolve({"hasError" : false,
"response": result});
}),
error : lang.hitch(this,function(result) {
deferred.resolve({"hasError" : true,
"response": result });
})
});
I've tried every possible variation of the contentArgs JSON and I have also tried using JSON.stringify on the contentArgs but having no joy. Any help is greatly appreciated. Thank you
Upvotes: 0
Views: 235
Reputation: 44685
Well, I'm assuming you're using dojo/_base/xhr
(there is a new dojo/request/xhr
module as well now, and dojo/_base/xhr
is deprecated).
There is one problem here, the content
parameter should only be used for query parameters, if I recall correctly. I can't say for sure, because that module is probably one of the worst documented modules of all.
The documentation says you should probably use the data
property in stead of content
but I tried that and it didn't fix it either.
However, after using the postData
property with JSON.stringify(contentArgs);
it does seem to work. So, try this:
xhr.put({
// The URL to request
url : url,
headers : {"Authorization" : "token 289543b6aca2454165451a1afcf115fa9a97", "Content-Type": "application/json"},
postData : JSON.stringify(contentArgs),
handleAs : "json",
load : function() {},
error : function() {}
});
You should probably also send the header Content-Type: application/json
to make sure the server knows it's sent as a JSON string.
However, if you're using Dojo 1.8+, I would recommend using dojo/request/xhr. It has a similar API, but it looks a bit cleaner (and is better documented as well):
xhr.put(url, {
headers : {"Authorization" : "token 289543b6aca2454165451a1afcf115fa9a97", "Content-Type": "application/json"},
data : JSON.stringify(contentArgs),
handleAs : "json"
});
Here's an example using both: http://jsfiddle.net/rvnkro8h/ I removed some stuff and used a different URL, but this should proberly send the request payload as JSON.
Upvotes: 1