2
I need to consult some Ceps in viacep API (https://viacep.com.br), when I run get below:
vm.buscarCEP = function(){
const cep = vm.empresaResponsavel.cep //RECEBE CEP DO CAMPO
const apiViaCep = `http://viacep.com.br/ws/${cep}/json/`
$http.get(apiViaCep).then(function(resp) { //CONSULTA NA API
vm.empresaResponsavel.logradouro = resp.data.logradouro
vm.empresaResponsavel.bairro = resp.data.bairro
vm.empresaResponsavel.cidade = resp.data.localidade
vm.empresaResponsavel.uf = resp.data.uf
}).catch(function(resp) {
console.log(resp.data.errors)
console.log("CEP NÃO RECONHECIDO.")
})
}
I get the following error in the browser console:
Requisição cross-origin bloqueada: A política de mesma origem (Same Origin Policy) impede a leitura do recurso remoto em http://viacep.com.br/ws/89700128/json/. (Motivo: símbolo 'authorization' faltando no cabeçalho CORS 'Access-Control-Allow-Headers' durante a pré-conexão CORS).
I am using Angularjs and Express/Node.
Below is an excerpt where I validate the user and pass to the backend a header with the token of the same, to check if it remains the same. I’m thinking that this header might be the problem.
function validateUser() {
const user = auth.getUser()
const authPage = '/auth.html'
const isAuthPage = $window.location.href.includes(authPage)
if (!user && !isAuthPage) {
$window.location.href = authPage
} else if (user && !user.isValid) {
auth.validateToken(user.token, (err, valid) => {
if (!valid) {
$window.location.href = authPage
} else {
user.isValid = true
$http.defaults.headers.common.Authorization = user.token
isAuthPage ? $window.location.href = '/' : $location.path('/dashboard')
}
})
}
}
I believe this link can help https://answall.com/questions/41322/pedido-cross-origin-blocked
– renan.meneses UFC
@Renan.menesesUFC do not know how JSONP (which seems to be the main proposal of the response that linked) would help in this specific problem, for Express (a framework for Nodejs that runs in the back end) already has libs that solve, such as https://www.npmjs.com/package/cors (there are others). The case there is only know how to configure, I would even do it by hand: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS and https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
– Guilherme Nascimento