Aurelia - HTTP
Neste capítulo, você aprenderá como trabalhar com solicitações HTTP no framework Aurelia.
Etapa 1 - Criar uma visualização
Vamos criar quatro botões que serão usados para enviar solicitações à nossa API.
app.html
<template>
<button click.delegate = "getData()">GET</button>
<button click.delegate = "postData()">POST</button>
<button click.delegate = "updateData()">PUT</button>
<button click.delegate = "deleteData()">DEL</button>
</template>
Etapa 2 - Criar um modelo de visualização
Para o envio de solicitações ao servidor, Aurelia recomenda fetchcliente. Estamos criando funções para todas as solicitações de que precisamos (GET, POST, PUT e DELETE).
import 'fetch';
import {HttpClient, json} from 'aurelia-fetch-client';
let httpClient = new HttpClient();
export class App {
getData() {
httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => {
console.log(data);
});
}
myPostData = {
id: 101
}
postData(myPostData) {
httpClient.fetch('http://jsonplaceholder.typicode.com/posts', {
method: "POST",
body: JSON.stringify(myPostData)
})
.then(response => response.json())
.then(data => {
console.log(data);
});
}
myUpdateData = {
id: 1
}
updateData(myUpdateData) {
httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {
method: "PUT",
body: JSON.stringify(myUpdateData)
})
.then(response => response.json())
.then(data => {
console.log(data);
});
}
deleteData() {
httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {
method: "DELETE"
})
.then(response => response.json())
.then(data => {
console.log(data);
});
}
}
Podemos executar o aplicativo e clicar GET, POST, PUT e DELbotões, respectivamente. Podemos ver no console que todas as solicitações são bem-sucedidas e o resultado é registrado.