Created
December 1, 2017 14:17
-
-
Save findcep/67dc17b66c54610a4cb9130cafdd2a4a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const validate_cep = (cep) => { | |
cep = cep.replace(/[^0-9]/gi, ""); | |
if (cep.length == 8) { | |
return cep; | |
} | |
throw `CEP "${cep}" format invalid` | |
} | |
const apiCep = (cep) => `https://api.findcep.com/v1/cep/${cep}.json` | |
let cep_search = validate_cep('01001-001'); | |
let myHeaders = new Headers(); | |
myHeaders.append('Referer', 'https://your-site.com'); | |
// Using callbacks | |
fetch(apiCep(cep_search), { headers: myHeaders}) | |
.then((responseObj) => { | |
responseObj.json() | |
.then((data) => console.log(data)); | |
}); | |
// Using async and await to make it more readable | |
var getCep = async (cep) => { | |
let response = await fetch(apiCep(cep_search)); | |
let cepJson = await response.json() | |
return cepJson; | |
} | |
getCep(cep_search).then(cep => console.log(cep)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment