4

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.

1
  • If anyone stumbles on the same error, just leave a comment here.
    – noogui
    Commented Feb 1, 2018 at 15:57

1 Answer 1

2

For read requests, you must send the token (and key) in the URL. For example:

https://api.stackexchange.com/2.2/me?site=stackoverflow&key=dp55hR5Wr9UhOJReA6F2gg((&access_token=26nor26ZCVN4y5vn94Zg(w))



For write operations (EG answers/{id}/upvote), you must use use HTTPS POST and then the key, access_token, and other parameters need to be form encoded.



Note that that doc page doesn't show you the full URL for security reasons. (I only showed the above full URL after invalidating the token shown.)

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .