Skip to content

Instantly share code, notes, and snippets.

@suissa
Created December 17, 2017 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suissa/e71f5dd66b8a87864896c5ec781ee654 to your computer and use it in GitHub Desktop.
Save suissa/e71f5dd66b8a87864896c5ec781ee654 to your computer and use it in GitHub Desktop.
const express = require( 'express' )
const axios = require( 'axios' )
const app = express()
const isCepValid = ( cep ) =>
( cep.length < 8 || cep.length > 9 )
? new Error( 'Cep inválido' )
: true
const sanitizeCEP = ( cep ) => cep.replace( /\D/g, '' )
const getCEP = ( req, res ) => {
const codeFormated = sanitizeCEP( req.query.code )
if ( isCepValid( codeFormated ) instanceof Error ) {
res.status( 400 )
return res.send( 'Cep inválido' )
}
axios.get( 'https://viacep.com.br/ws/' + codeFormated + '/json' )
.then( function ( response ) {
console.log( response )
res.json( response.data )
} )
.catch( function ( error ) {
console.log( error )
} )
}
app.get( '/cep', getCEP )
app.listen( 9000 )
console.log( 'Server started! At http://localhost:9000' )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment