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
});
Invest-app (CRUD)
Arquivos
invest-app
├── css
│ └── style.css
├── index.html
├── js
│ ├── components
│ │ ├── InvestmentCard.js
│ │ ├── InvestmentForm.js
│ │ └── Modal.js
│ ├── lib
│ │ ├── dom.js
│ │ ├── format.js
│ │ └── investments.js
│ ├── main.js
│ └── services
│ └── storage.js
├── package-lock.json
├── package.json
├── postcss.config.js
├── public
│ └── vite.svg
└── tailwind.config.js
Arquivos
invest-app
├── css
│ └── style.css
├── index.html
├── js
│ ├── components
│ │ ├── InvestmentCard.js
│ │ ├── InvestmentForm.js
│ │ └── Modal.js
│ ├── lib
│ │ ├── dom.js
│ │ ├── format.js
│ │ └── investments.js
│ ├── main.js
│ └── services
│ └── storage.js
├── package-lock.json
├── package.json
├── postcss.config.js
├── public
│ └── vite.svg
└── tailwind.config.js
/codes/w3c/fetch-api/invest-app/.env.example
VITE_APP_SUPABASE_KEY=
VITE_APP_SUPABASE_URL=
/codes/w3c/fetch-api/invest-app/.env.example
VITE_APP_SUPABASE_KEY=
VITE_APP_SUPABASE_URL=
/codes/w3c/fetch-api/invest-app/js/service/storage.js
const API_TOKEN = import.meta.env.VITE_APP_SUPABASE_KEY;
const API_URL = import.meta.env.VITE_APP_SUPABASE_URL;
async function create(resource, data) {}
async function read(resource, id) {}
async function update(resource, id, data) {}
async function remove(resource, id) {}
export default { create, read, update, remove };
/codes/w3c/fetch-api/invest-app/js/service/storage.js
const API_TOKEN = import.meta.env.VITE_APP_SUPABASE_KEY;
const API_URL = import.meta.env.VITE_APP_SUPABASE_URL;
async function create(resource, data) {}
async function read(resource, id) {}
async function update(resource, id, data) {}
async function remove(resource, id) {}
export default { create, read, update, remove };
Create a investment
/codes/w3c/fetch-api/invest-app/js/service/storage.js
async function create(resource, data) {
resource = `${API_URL}/${resource}`;
const options = {
headers: {
apikey: API_TOKEN,
Authorization: `Bearer ${API_TOKEN}`,
Prefer: 'return=representation',
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(data),
};
const res = await fetch(resource, options);
const createdData = await res.json();
return createdData?.[0];
}
/codes/w3c/fetch-api/invest-app/js/service/storage.js
async function create(resource, data) {
resource = `${API_URL}/${resource}`;
const options = {
headers: {
apikey: API_TOKEN,
Authorization: `Bearer ${API_TOKEN}`,
Prefer: 'return=representation',
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(data),
};
const res = await fetch(resource, options);
const createdData = await res.json();
return createdData?.[0];
}
import Storage from './js/services/storage.js';
const investment = {
name: "Tesouro Selic 2029",
value: 10000,
origin: "Tesouro Direto",
category: "Pós",
interest: "100% Selic",
created_at: "2021-09-10T00:00:00-03:00",
};
Storage.create('investments', investment);
import Storage from './js/services/storage.js';
const investment = {
name: "Tesouro Selic 2029",
value: 10000,
origin: "Tesouro Direto",
category: "Pós",
interest: "100% Selic",
created_at: "2021-09-10T00:00:00-03:00",
};
Storage.create('investments', investment);
Read investments
/codes/w3c/fetch-api/invest-app/js/service/storage.js
async function read(resource, id) {
resource = id
? `${API_URL}/${resource}?id=eq.${id}`
: `${API_URL}/${resource}`;
const options = {
headers: {
apikey: API_TOKEN,
Authorization: `Bearer ${API_TOKEN}`,
},
method: 'GET',
};
const res = await fetch(resource, options);
return await res.json();
}
/codes/w3c/fetch-api/invest-app/js/service/storage.js
async function read(resource, id) {
resource = id
? `${API_URL}/${resource}?id=eq.${id}`
: `${API_URL}/${resource}`;
const options = {
headers: {
apikey: API_TOKEN,
Authorization: `Bearer ${API_TOKEN}`,
},
method: 'GET',
};
const res = await fetch(resource, options);
return await res.json();
}
import Storage from './js/services/storage.js';
Storage.read('investments');
Storage.read('investments', 1);
import Storage from './js/services/storage.js';
Storage.read('investments');
Storage.read('investments', 1);
Update a investment
/codes/w3c/fetch-api/invest-app/js/service/storage.js
async function update(resource, id, data) {
resource = `${API_URL}/${resource}?id=eq.${id}`;
const options = {
headers: {
apikey: API_TOKEN,
Authorization: `Bearer ${API_TOKEN}`,
Prefer: 'return=representation',
'Content-Type': 'application/json',
},
method: 'PATCH',
body: JSON.stringify(data),
};
const res = await fetch(resource, options);
const updatedData = await res.json();
return updatedData?.[0];
}
/codes/w3c/fetch-api/invest-app/js/service/storage.js
async function update(resource, id, data) {
resource = `${API_URL}/${resource}?id=eq.${id}`;
const options = {
headers: {
apikey: API_TOKEN,
Authorization: `Bearer ${API_TOKEN}`,
Prefer: 'return=representation',
'Content-Type': 'application/json',
},
method: 'PATCH',
body: JSON.stringify(data),
};
const res = await fetch(resource, options);
const updatedData = await res.json();
return updatedData?.[0];
}
import Storage from './js/services/storage.js';
Storage.update('investments', 1, { value: 15000 });
import Storage from './js/services/storage.js';
Storage.update('investments', 1, { value: 15000 });
Delete a investment
/codes/w3c/fetch-api/invest-app/js/service/storage.js
async function remove(resource, id) {
resource = `${API_URL}/${resource}?id=eq.${id}`;
const options = {
headers: {
apikey: API_TOKEN,
Authorization: `Bearer ${API_TOKEN}`,
},
method: 'DELETE',
};
const res = await fetch(resource, options);
return res.ok;
}
/codes/w3c/fetch-api/invest-app/js/service/storage.js
async function remove(resource, id) {
resource = `${API_URL}/${resource}?id=eq.${id}`;
const options = {
headers: {
apikey: API_TOKEN,
Authorization: `Bearer ${API_TOKEN}`,
},
method: 'DELETE',
};
const res = await fetch(resource, options);
return res.ok;
}
import Storage from './js/services/storage.js';
Storage.remove('investments', 1);
import Storage from './js/services/storage.js';
Storage.remove('investments', 1);