-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
49 lines (36 loc) · 1.28 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
var submitButton = document.querySelector('#app form button')
var zipCodeField = document.querySelector('#app form input')
var content = document.querySelector('#app main')
submitButton.addEventListener('click', run)
function run(event){
event.preventDefault()
var zipCode = zipCodeField.value
zipCode = zipCode.replace(' ', '')
zipCode = zipCode.replace('.', '')
zipCode = zipCode.trim()
axios.get(`https://viacep.com.br/ws/${zipCode}/json/`)
.then(function(response){
if (response.data.erro){
throw new Error('CEP inválido.') // caso o cep tenha quantidade de caracteres certos, porem invalido
}
content.innerHTML = ''
renderData(response.data.logradouro)
renderData(response.data.bairro)
renderData(`${response.data.localidade} - ${response.data.uf}`)
console.log(response.data)
})
.catch(function(error){
console.log(error)
content.innerHTML = ''
renderData('Ops, algo deu errado!')
})
.finally(function(){
console.log('Requisição realizada com sucesso.')
})
}
function renderData(value){
var line = document.createElement('p')
var textLine = document.createTextNode(value)
line.appendChild(textLine)
content.appendChild(line)
}