Ashwin
Ashwin

Reputation: 1960

GitHub: How to set headers for ajax request?

How do I set authorization headers for ajax request to make request on GitHub account?

I have created Personal Access Tokens on GitHub to use it with ajax for authentication to perform operations on my repository.

ajax request is made as shown below:

var apiDomain = 'https://api.github.com',
    api="/users/" + username;
    $.ajax({
        beforeSend: function (xhr) {
            xhr.setRequestHeader ("Authorization", "token 8da3512a16c3fc0d33d8932ca37e6f5bc4c695c0");
        },
        url:apiDomain+api+'?callback=testUser',
        dataType:'script'
    });

I get the response data as expected. However, the ajax call is unauthenticated and I always see the following on the meta object

X-RateLimit-Limit: "60"
X-RateLimit-Remaining: "55"
X-RateLimit-Reset: "1387964695"
status: 200

If the ajax request is authenticated I should be able to make ~5000 requests.

How do I use my Personal Access Tokens to make more ajax requests on GitHub?

Upvotes: 3

Views: 1375

Answers (1)

Ashwin
Ashwin

Reputation: 1960

Passing the access_token as a query parameter solved the problem.

Here is the modified version with the query parameter "access_token"

var apiDomain = 'https://api.github.com',
    api="/users/" + username;
    $.ajax({
        url:apiDomain+api+'?callback=testUser&access_token=8da3512a16c3fc0d33d8932ca37e6f5bc4c695c0',
        dataType:'script'
    });

P.S: The comment in the question helped me find the solution. Thanks @VonC

Upvotes: 6

Related Questions