Requisição Assíncrona
Fetch API
fetch(resource)
fetch(resource, options)
fetch(resource)
fetch(resource, options)
Exemplo
/codes/w3c/fetch-api/via-cep/index.js
async function getCep(cep) {
const resource = `https://viacep.com.br/ws/${cep}/json/`;
const res = await fetch(resource);
return await res.json();
}
const cep = '58015430';
// then
const resource = `https://viacep.com.br/ws/${cep}/json/`;
fetch(resource)
.then((res) => res.json())
.then((data) => console.log(data));
// async await
const data = await getCep(cep);
console.log(data);
/codes/w3c/fetch-api/via-cep/index.js
async function getCep(cep) {
const resource = `https://viacep.com.br/ws/${cep}/json/`;
const res = await fetch(resource);
return await res.json();
}
const cep = '58015430';
// then
const resource = `https://viacep.com.br/ws/${cep}/json/`;
fetch(resource)
.then((res) => res.json())
.then((data) => console.log(data));
// async await
const data = await getCep(cep);
console.log(data);
Cross-Origin Resource Sharing (CORS)
- Access-Control-Allow-Origin
- Access-Control-Allow-Methods
- Access-Control-Allow-Headers
- Access-Control-Allow-Credentials
- Access-Control-Max-Age
HTTP/1.1 200 OK
Server: nginx/1.22.0
Date: Seg, 11 Sep 2023 12:03:17 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Expires: Sun, 10 Sep 2023 13:03:17 GMT
Cache-Control: max-age=3600, public
Pragma: public
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type, X-Request-With, X-Requested-By
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
{
"cep": "58015-430",
"logradouro": "Avenida Primeiro de Maio",
"complemento": "até 469/470",
"bairro": "Jaguaribe",
"localidade": "João Pessoa",
"uf": "PB",
"ibge": "2507507",
"gia": "",
"ddd": "83",
"siafi": "2051"
}
HTTP/1.1 200 OK
Server: nginx/1.22.0
Date: Seg, 11 Sep 2023 12:03:17 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Expires: Sun, 10 Sep 2023 13:03:17 GMT
Cache-Control: max-age=3600, public
Pragma: public
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type, X-Request-With, X-Requested-By
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
{
"cep": "58015-430",
"logradouro": "Avenida Primeiro de Maio",
"complemento": "até 469/470",
"bairro": "Jaguaribe",
"localidade": "João Pessoa",
"uf": "PB",
"ibge": "2507507",
"gia": "",
"ddd": "83",
"siafi": "2051"
}
O Fetch API é uma alternativa ao XMLHttpRequest
function makeRequest (method, url) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
// xhr.setRequestHeader('Authorization', `Bearer TOKEN`);
xhr.onload = resolve;
xhr.onerror = reject;
xhr.send();
});
}
const cep = '58015430';
const resource = `https://viacep.com.br/ws/${cep}/json/`;
makeRequest('GET', resource)
.then(function (e) {
console.log(e.target.response);
}, function (e) {
// handle errors
});
function makeRequest (method, url) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
// xhr.setRequestHeader('Authorization', `Bearer TOKEN`);
xhr.onload = resolve;
xhr.onerror = reject;
xhr.send();
});
}
const cep = '58015430';
const resource = `https://viacep.com.br/ws/${cep}/json/`;
makeRequest('GET', resource)
.then(function (e) {
console.log(e.target.response);
}, function (e) {
// handle errors
});
Monitor-app (CRUD)
Arquivos
monitor-app
├── back
│ ├── db.json
│ ├── package-lock.json
│ ├── package.json
│ └── src
│ └── server.js
└── front
├── css
│ └── style.css
├── index.html
├── js
│ ├── components
│ │ ├── HostForm.js
│ │ ├── HostTableRow.js
│ │ └── Modal.js
│ ├── lib
│ │ ├── dom.js
│ │ └── hosts.js
│ ├── main.js
│ └── services
│ └── storage.js
├── package-lock.json
├── package.json
├── public
│ └── vite.svg
└── vite.config.js
Arquivos
monitor-app
├── back
│ ├── db.json
│ ├── package-lock.json
│ ├── package.json
│ └── src
│ └── server.js
└── front
├── css
│ └── style.css
├── index.html
├── js
│ ├── components
│ │ ├── HostForm.js
│ │ ├── HostTableRow.js
│ │ └── Modal.js
│ ├── lib
│ │ ├── dom.js
│ │ └── hosts.js
│ ├── main.js
│ └── services
│ └── storage.js
├── package-lock.json
├── package.json
├── public
│ └── vite.svg
└── vite.config.js
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
const API_URL = '/api';
async function create(resource, data) {}
async function read(resource) {}
async function update(resource, data) {}
async function remove(resource) {}
export default { create, read, update, remove };
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
const API_URL = '/api';
async function create(resource, data) {}
async function read(resource) {}
async function update(resource, data) {}
async function remove(resource) {}
export default { create, read, update, remove };
/codes/w3c/fetch-api/monitor-app/front/vite.config.js
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
server: {
open: 'index.html',
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
});
/codes/w3c/fetch-api/monitor-app/front/vite.config.js
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
server: {
open: 'index.html',
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
});
Create a host
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
async function create(resource, data) {
resource = `${API_URL}/${resource}`;
const options = {
headers: {
'Content-Type': 'application/json',
},
method: 'post',
body: JSON.stringify(data),
};
const res = await fetch(resource, options);
const createdData = await res.json();
return createdData;
}
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
async function create(resource, data) {
resource = `${API_URL}/${resource}`;
const options = {
headers: {
'Content-Type': 'application/json',
},
method: 'post',
body: JSON.stringify(data),
};
const res = await fetch(resource, options);
const createdData = await res.json();
return createdData;
}
import Storage from './js/services/storage.js';
const host = {
name: "DNS Server",
address: "1.1.1.1"
};
Storage.create('hosts', host);
import Storage from './js/services/storage.js';
const host = {
name: "DNS Server",
address: "1.1.1.1"
};
Storage.create('hosts', host);
Read hosts
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
async function read(resource) {
resource = `${API_URL}/${resource}`;
const res = await fetch(resource);
return await res.json();
}
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
async function read(resource) {
resource = `${API_URL}/${resource}`;
const res = await fetch(resource);
return await res.json();
}
import Storage from './js/services/storage.js';
Storage.read('hosts');
Storage.read('hosts/3');
import Storage from './js/services/storage.js';
Storage.read('hosts');
Storage.read('hosts/3');
Update a host
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
async function update(resource, data) {
resource = `${API_URL}/${resource}`;
const options = {
headers: {
'Content-Type': 'application/json',
},
method: 'put',
body: JSON.stringify(data),
};
const res = await fetch(resource, options);
const createdData = await res.json();
return createdData;
}
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
async function update(resource, data) {
resource = `${API_URL}/${resource}`;
const options = {
headers: {
'Content-Type': 'application/json',
},
method: 'put',
body: JSON.stringify(data),
};
const res = await fetch(resource, options);
const createdData = await res.json();
return createdData;
}
import Storage from './js/services/storage.js';
Storage.update('hosts/3', { name: 'Cloudflare DNS', addres: '1.1.1.1' });
import Storage from './js/services/storage.js';
Storage.update('hosts/3', { name: 'Cloudflare DNS', addres: '1.1.1.1' });
Delete a host
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
async function remove(resource) {
resource = `${API_URL}/${resource}`;
const options = {
method: 'delete',
};
const res = await fetch(resource, options);
return res.ok;
}
/codes/w3c/fetch-api/monitor-app/front/js/service/storage.js
async function remove(resource) {
resource = `${API_URL}/${resource}`;
const options = {
method: 'delete',
};
const res = await fetch(resource, options);
return res.ok;
}
import Storage from './js/services/storage.js';
Storage.remove('hosts/3');
import Storage from './js/services/storage.js';
Storage.remove('hosts/3');