Skip to content

Instantly share code, notes, and snippets.

@findcep
Created December 1, 2017 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save findcep/67dc17b66c54610a4cb9130cafdd2a4a to your computer and use it in GitHub Desktop.
Save findcep/67dc17b66c54610a4cb9130cafdd2a4a to your computer and use it in GitHub Desktop.
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