XMLHttpRequest (XHR)
- Asynchronous JavaScript and XML (AJAX)
- Request HTTP (GET XML)
- Request HTTP (GET PIPED)
- Request HTTP (GET JSON)
- Request HTTP (GET JSONP)
- Request HTTP (POST JSON, Token)
- Handling Request HTTP
Asynchronous JavaScript and XML (AJAX)
Reference: Wikipedia
Classic web application model (synchronous)
Reference: HTTP Debug
Ajax web application model (asynchronous)
Reference: HTTP Debug
Request HTTP (GET XML)
ViaCEP API: https://viacep.com.br/ws/58015430/xml/
$ curl -i https://viacep.com.br/ws/58015430/xml/
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Thu, 10 May 2018 19:36:06 GMT
Content-Type: application/xhtml+xml
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, OPTIONS
Access-Control-Allow-Headers: Content-Type, X-Request-With, X-Requested-By
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Expires: Thu, 10 May 2018 20:36:06 GMT
Cache-Control: max-age=3600
Cache-Control: public
<?xml version="1.0" encoding="UTF-8"?>
<xmlcep>
<cep>58015-430</cep>
<logradouro>Avenida Primeiro de Maio</logradouro>
<complemento>até 469/470</complemento>
<bairro>Jaguaribe</bairro>
<localidade>João Pessoa</localidade>
<uf>PB</uf>
<unidade></unidade>
<ibge>2507507</ibge>
<gia></gia>
</xmlcep>
function makeRequest(method, url, callback) {
const xhr = new XMLHttpRequest()
xhr.onload = () => callback(xhr.responseXML)
xhr.open(method, url)
xhr.send()
}
makeRequest('GET', 'https://viacep.com.br/ws/58015430/xml/', (response) => {
console.log(response)
// XML DOM
console.log(response.getElementsByTagName('localidade')[0].childNodes[0].nodeValue)
})
Request HTTP (GET PIPED)
ViaCEP API: https://viacep.com.br/ws/58015430/piped/
$ curl -i https://viacep.com.br/ws/58015430/piped/
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Thu, 10 May 2018 19:29:38 GMT
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Expires: Thu, 10 May 2018 20:29:38 GMT
Cache-Control: max-age=3600
Cache-Control: public
cep:58015-430|logradouro:Avenida Primeiro de Maio|complemento:até 469/470|bairro:Jaguaribe|localidade:João Pessoa|uf:PB|unidade:|ibge:2507507|gia:
function makeRequest(method, url, callback) {
const xhr = new XMLHttpRequest()
xhr.onload = () => callback(xhr.responseText)
xhr.open(method, url)
xhr.send()
}
makeRequest('GET', 'https://viacep.com.br/ws/58015430/piped/', (response) => {
console.log(response)
})
Cross-Origin Resource Sharing (CORS):
Safari: Origin http://127.0.0.1:5500 is not allowed by Access-Control-Allow-Origin.
Chrome: Failed to load https://viacep.com.br/ws/58015430/piped/: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://127.0.0.1:5500’ is therefore not allowed access.
Request HTTP (GET JSON)
ViaCEP API: https://viacep.com.br/ws/58015430/json/
$ curl -i https://viacep.com.br/ws/58015430/json/
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Thu, 10 May 2018 19:27:14 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, OPTIONS
Access-Control-Allow-Headers: Content-Type, X-Request-With, X-Requested-By
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Expires: Thu, 10 May 2018 20:27:14 GMT
Cache-Control: max-age=3600
Cache-Control: public
{
"cep": "58015-430",
"logradouro": "Avenida Primeiro de Maio",
"complemento": "até 469/470",
"bairro": "Jaguaribe",
"localidade": "João Pessoa",
"uf": "PB",
"unidade": "",
"ibge": "2507507",
"gia": ""
}
function makeRequest(method, url, callback) {
const xhr = new XMLHttpRequest()
xhr.onload = () => callback(xhr.responseText)
xhr.open(method, url)
xhr.send()
}
function showContent(response) {
console.log(response)
const cep = JSON.parse(response)
console.log(cep.localidade)
}
makeRequest(
'GET',
'https://viacep.com.br/ws/58015430/json/',
response => showContent(response)
)
Request HTTP (GET JSONP)
ViaCEP API: https://viacep.com.br/ws/58015430/json/?callback=showContent
$ curl -i https://viacep.com.br/ws/58015430/json/?callback=showContent
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Thu, 10 May 2018 19:52:54 GMT
Content-Type: application/javascript; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, OPTIONS
Access-Control-Allow-Headers: Content-Type, X-Request-With, X-Requested-By
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Expires: Thu, 10 May 2018 20:52:54 GMT
Cache-Control: max-age=3600
Cache-Control: public
showContent({
"cep": "58015-430",
"logradouro": "Avenida Primeiro de Maio",
"complemento": "até 469/470",
"bairro": "Jaguaribe",
"localidade": "João Pessoa",
"uf": "PB",
"unidade": "",
"ibge": "2507507",
"gia": ""
});%
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="js/main.js"></script>
<script src="https://viacep.com.br/ws/58015430/json/?callback=showContent>"></script>
</body>
</html>
function showContent(response) {
console.log(reponse)
}
Request HTTP (POST JSON, Token)
SendGrid API V3: https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html:
$ curl --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header 'Authorization: Bearer YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": "example@example.com"}]}],"from": {"email": "example@example.com"},"subject": "Hello, World!","content": [{"type": "text/plain", "value": "Heya!"}]}'
{
"personalizations": [
{
"to": [
{ "email": "example@example.com" }
]
}
],
"from": { "email": "example@example.com" },
"subject": "Hello, World!",
"content": [
{
"type": "text/plain",
"value": "Heya!"
}
]
}
const email = {
"personalizations": [
{
"to": [
{ "email": "example@example.com" }
]
}
],
"from": { "email": "example@example.com" },
"subject": "Hello, World!",
"content": [
{
"type": "text/plain",
"value": "Heya!"
}
]
}
function makeRequest(method, url, data, callback) {
const xhr = new XMLHttpRequest()
xhr.onload = () => callback(xhr.responseText)
xhr.setRequestHeader("Authorization", "Bearer YOUR_API_KEY")
xhr.setRequestHeader("Content-Type", "application/json")
xhr.open(method, url)
xhr.send(data)
}
function showContent(response) {
console.log(response)
}
makeRequest(
'POST',
'https://api.sendgrid.com/v3/mail/send',
email,
response => showContent(response)
)
Handling Request HTTP
const xhr = new XMLHttpRequest();
function makeRequest(method, url) {
if (!xhr) {
console.log('Cannot create an XMLHTTP instance');
return false;
}
xhr.onreadystatechange = showContents;
xhr.open(method, url);
xhr.send();
}
function showContents() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('There was a problem with the request.');
}
}
}
makeRequest('GET', 'https://viacep.com.br/ws/58015430/json/')