I use a class API
based on JQuery
to work with everything related to api
. Depending on the api
to use the token
will have a different operation, in my case my API
uses the token by Header
of the petición HTTP
var api; // Variable api global para todos los .js
class Api {
// Se usa el constructor para crear nuestra api con la url correcta
constructor(host, port, protocol, token) {
this.host = host;
this.port = port;
this.protocol = protocol;
this.token = token;
this.baseUrl = protocol + host + ":" + port + "/";
this.result = undefined;
this.req = undefined;
};
// Creamos las funciones GET, POST y les asignamos un succes CallOut para recuperar los datos de la peticion
Get(req, async) {
this.req = req;
//Creamos una peticion ajax usando jQuery, aqui deberias de crear la petición usando los parámetros que necessites para tu API
$.ajax({ async: async, type:'get', url: this.baseUrl + req, headers: {
"token": this.token
}, success: successCallOut, error: function(xhr,status,error){
console.log("-----------Error Api GET " + this.baseUrl + req + "------------------");
console.log("Status: " + status);
console.log("Error :" + error);
console.log(xhr);
console.log("---------------End Error----------------");
this.result = "error";
}});
if(!async){
while (this.result == undefined) {}
return this.result;
}
};
GetSync(req){
return this.Get(req, false);
};
GetAsync(req){
return this.Get(req, true);
};
Post(req, body, bodyType, async) {
this.req = req;
$.ajax({ async: async, type:'post', url: this.baseUrl + req, data: body, contentType: bodyType, headers: {
"token": this.token
}, success: successCallOut, error: function(xhr,status,error){
console.log("-----------Error Api POST " + api.baseUrl + req + "------------------");
console.log("Body: \"" + bodyType + "\" " + body);
console.log("Status: " + status);
console.log("Error: " + error);
console.log(xhr);
console.log("---------------End Error----------------");
this.result = "error";
}});
if(!async){
while (this.result == undefined) {}
return this.result;
}
}
PostJson(req, body, async){
return this.Post(req, body, "application/json", async);
}
PostJsonSync(req, body){
return this.Post(req, body, "application/json", false);
}
PostJsonAsync(req, body){
return this.Post(req, body, "application/json", true);
}
SetToken(req){
$.ajax({ async: false, type:'get', url: this.baseUrl + req,
success: tokenCallOut, error: function(xhr,status,error){
console.log("-----------Error Api GET " + this.baseUrl + req + "------------------");
console.log("Status: " + status);
console.log("Error :" + error);
console.log(xhr);
console.log("---------------End Error----------------");
this.token = "error";
}});
}
};
function tokenCallOut(data){
console.log("API TOKEN SUCCESS");
api.token = data;
}
// Aqui es donde trabajaremos con los resultados de la petición, por ejemplo tu haces la peticion a /productos y la redirijes a la funcion ProcesarProductos(), mi ejemplo es /news/last
function successCallOut(data){
console.log("API GET/POST SUCCESS");
api.result = data;
switch (api.req){
case "auth":
alert(data['token']);
break;
case "handle":
alert(data);
break;
case "news/last":
ShowLastNews();
break;
}
};
function ShowLastNews() {
//Recuperamos el resultado de la peticion
var news = api.result;
//Mostramos el resultado de la petición
console.log(news);
//Aqui és donde tienes que hacer los GetElementById() y assignarles el contenido de la petición
}
More information of AJAX
with JQuery
link
To work with this class is very easy you just need to call the function GET
of the class
<script type="text/javascript">
window.onload = IndexLoadCode;
function IndexLoadCode() {
api = new Api('localhost','3000','http://','');
api.SetToken('auth?user=main');
api.GetSync('news/last');
}
</script>
Which returns the next result
In my case as the request that returns the api and returns it as JSON I get the object directly as JSON and I do not need the JSON.Parse ()
To add the content to the elements, it's that simple
$(#id).html(api.result.contenido);
You can also add it by creating elements DOM
Create elements of the DOM with jquery
To add css
link
link
To change the image use attr
link
$(#img).attr('src',api.result.src);
Extra information on how to work with JSON
Tour JSON with JQuery
How can I traverse a json array and get its values to show them in the view?
I hope you have not left me anything and that it will help you!