So I'm able to use API calls like:
https://api.stackexchange.com/2.2/questions?pagesize=30&order=desc&sort=activity&site=stackoverflow
to display a list of questions. This is easy as it doesn't ask for accesstoken
with the request.
Now I decided to level up and fetch data related to the signed-in user. Of course it's going to ask an accesstoken
to authorize the request.
How do I implement this using only JS + HTML code?
I know how to fetch the accesstoken
once the user is authenticated using this:
var = myAccessToken;
SE.authenticate({
success: function(data) {
myAccessToken = data['accessToken'];
displayUserProfile('https://api.stackexchange.com/2.2/me?order=desc&sort=reputation&site=stackoverflow');
},
error: function(data) { console.log("OAuth Error!", data) },
scope: ['read_inbox'],
networkUsers: true,
redirect_uri:'http://localhost:80/XMLHttpRequest/index.html'
});
So this variable myAccessToken = data['accessToken'];
now holds the accesstoken. But I don't know how to use it.
Should I do it like this?
function displayUserProfile(url) {
const xhr = new window.XMLHttpRequest()
xhr.open('get', url, true)
xhr.setRequestHeader('Authorization', 'Bearer ' + myAccessToken);
xhr.responseType = 'json'
xhr.onload = () => {
if (xhr.status === 200) {
console.log("success",xhr.response)
}
} else {
console.log("fail",xhr.response);
}
}
xhr.send();
}
The URL being passed is what's indicated in the Usage of /me docs which is:
https://api.stackexchange.com/2.2/me?order=desc&sort=reputation&site=stackoverflow
wherein I get the error:
https://api.stackexchange.com/2.2/me?order=desc&sort=reputation&site=stackoverflow 400 (Bad Request)
In short, using the acquired accesstoken
, how do I make a proper request to /me
so I can fetch my private info (displayname, reputation, etc.) after signing in.