Using Twitter API with JavaScript
The answer is quite a simple: use Fetch API.
JavaScript is so powerful, especially on modern browsers such as Chrome. It’s always evolving, and providing solutions for its faults. I also encountered a problem with JavaScript, but there’s already one for the issue.
#XMLHTTPRequest
JavaScript already has a method to get contents on the Web. XMLHTTPRequest has
various options, and it’s more generic than the name indicates: it can be used
for any data, and any protocol the browser supports. It’s also possible to
modify headers with setRequestHeader
.
However, XMLHTTPRequest sometimes brings unexpected results: the header contains
some variables specified by the browser, and some of them can’t be removed.
In my case, Cookie
header caused an error.
#Fetch API Fetch API is new. The API is defined by WHATWG. The specification is available on https://fetch.spec.whatwg.org/, but note that it’s “living standard”. The last update is on 18 March 2016. The specification can be changed later. MDN provides information about browser compatiblity I recommend to refer the page before you use the API.
##Using Fetch API to Get the Bearer Token of Twitter Fortunately, what I’m developing is a Chrome extension, and I don’ have to be bothered by browsers without Fecth API. I’ll show the exact code of my extension for a example.
fetch("https://api.twitter.com/oauth2/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"Authorization": "Basic " + btoa(CONSUMER_KEY + ":" + CONSUMER_SECRET)
},
body: "grant_type=client_credentials"});
It’s really simple, isn’t it? The Authorization
part may look redundant because
XMLHTTPRequest can set the header automatically by passing the credentials
as parameters for open
or by including them to the URI. It’s impossible for
now, but the new standard of Fetch API has authorizationValue, a new variable for Authorization
.
Stay tuned!