Cross-origin requests are being blocked

2

I need to consult some zip codes in viacep API ( link ), 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'm using AngularJS and Express / Node.

Below is an excerpt where the user is valid, and a header with the token is passed to the backend to verify that it remains the same. I'm thinking 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')
      }
    })
  }
}
    
asked by anonymous 04.05.2018 / 04:29

1 answer

0

Add the cors:

npm install cors --save

No node js add this code

const cors = require('cors');
app.use(cors());
    
04.05.2018 / 14:47