I'm trying to make a text post to Tumblr using their API and chrome_ex_oauth.
- API: http://www.tumblr.com/docs/en/api/v2#posting
- chrome_ex_oauth: http://code.google.com/chrome/extensions/tut_oauth.html
The whole process of getting authorized works. What I can't get to work is doing a POST. I'm doing the following:
Edit: I've updated the code to reflect Rob W's correct suggestion about the body field
var stringify = function (parameters) {
var params = [];
for(var p in parameters) {
params.push(encodeURIComponent(p) + '=' +
encodeURIComponent(parameters[p]));
}
return params.join('&');
};
var onAuthorized = function() {
var url = 'http://api.tumblr.com/v2/blog/jindie.tumblr.com/post';
var request = {
'method': 'POST',
'headers':{
'Content-Type':'application/x-www-form-urlencoded'
},
'body': stringify({
'type': 'text',
'state': 'draft',
'title': 'Test post...',
'body': 'Hello, World!'
})
};
oauth.sendSignedRequest(url, function(responseText, xhr){alert(responseText);}, request);
};
oauth.authorize(onAuthorized);
I've been examining the code, and thinking what could be wrong, but I seriously have no idea. Do you?
Do you know where I'm going wrong?
When the documentation doesn't help have a look at the source code, chrome_ex_oauth.js
.
You have to use 'body'
instead of 'parameters'
:
var request = {
'method': 'POST',
'body': {
Debugging
In order to find the cause, I followed these steps (annotated my thoughts):
- Apparently, the post body is empty. So, the implementation of the API must be wrong.
Ctrl + F
sendSignedRequest
:ChromeExOAuth.prototype.sendSignedRequest = function(url, callback, opt_params) { var method = opt_params && opt_params['method'] || 'GET'; var body = opt_params && opt_params['body'] || null; var params = opt_params && opt_params['parameters'] || {}; var headers = opt_params && opt_params['headers'] || {};
var signedUrl = this.signURL(url, method, params);
// Hmm...? Where is `params` being passed...? ChromeExOAuth.sendRequest(method, signedUrl, headers, body, function (xhr) { if (xhr.readyState == 4) { callback(xhr.responseText, xhr); } }); };signURL
doesn't modifyparams
, so that's not a problem.- Ctrl + F
sendRequest
:ChromeExOAuth.sendRequest = function(method, url, headers, body, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(data) { callback(xhr, data); } xhr.open(method, url, true); if (headers) { . . . } xhr.send(body); // <-- !!! };
- Got it!
body
has to be used instead ofparameters
. - Backtracks the
body
variable to therequest['body']
(see 2).
来源:https://stackoverflow.com/questions/10568812/making-a-post-request-to-tumblrs-api-inside-a-chrome-extension