Authentication and jQuery

Authentication and jQuery

in API Development

Posted by: cawtx.2016

cawtx.2016

I’ve been able to access all authenticated endpoints with C#, but am having problems with jQuery. Tried both $.ajax() and $.getJSON(). Also tried different settings in the function which are commented out in the code below.

How do you authenticate with jQuery.ajax() and/or $.getJson()?

$(document).ready(function () {
$(“button”).on(“click”, function () {
$.ajax(‘https://api.guildwars2.com/v2/characters’, {
type: “GET”,
dataType: “json”,
//beforeSend : function (xhr) {xhr.setRequestHeader(“Authorization”, “Bearer <token>”)},
//headers : {Authorization : “Bearer <token>”},
xhrFields: {Authorization : “Bearer <token>”},
complete : function (resp) {console.log(resp);},
error: function(jqXHR, textStatus, errorThrown) {console.log(textStatus);}
});});});

Authentication and jQuery

in API Development

Posted by: cawtx.2016

cawtx.2016

Not mentioned in OP, but a setting of
data : {"access_token" : “<token>”}
does work and allows me access to the endpoint, but this does not seem to be a satisfying solution which is why I posted the question and I am interested if there is a better way.

Authentication and jQuery

in API Development

Posted by: Nier.6408

Nier.6408

You can simply access APIs with jQuery code like this:

var url = "https://api.guildwars2.com/v2/account?access_token=" + my_api_key;

$.getJSON(url, function(data) {
// use your data
}).fail(function(xhr) {
console.log("Error: " + $.parseJSON(xhr.responseText).text);
});

EDIT:
The endpoint uses GET method to authenticate your token. So you can add it in the URL like above or set it in the data settings in jQuery’s $.ajax or $.getJSON methods.

(edited by Nier.6408)