Cross-origin requests are being blocked

Asked

Viewed 1,515 times

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.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

2 answers

0

I had the same problem when creating my api, the difference is that I use Angular 8 instead of Angularjs, you can install Cors with npm install cors and use the following configuration in the Node

const cors = require('cors');
[...]
const corsOptions = {
  origin: 'http://origin-angular-example.com:4200',
  optionsSuccessStatus: 200
}
[...]
app.use(cors(corsOptions));

[...] are spaces in your code if there are...

In addition you can try to install this extension: https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc in your browser and enable it.

0

Add the Cors:

npm install cors --save

In Node js add this code

const cors = require('cors');
app.use(cors());
  • Didn’t work out ://

  • Can you do a test? Add this plugin to the browser ? https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=pt-BR&utm_source=chrome-ntp-launcher

  • Lucas, thanks for the help!! Just enable and perform the test? I did that, returned the same error. I also performed the test with another api, the table fipe: http://fipeapi.appspot.com/ and in addition to the previous error, returned with HTTP status code 405.

  • At first yes. Status 405 is that the method is not enabled, which does not make any sense ... I’m going to run a test here and take some data from these Apis and then give you an opinion of what happened.

  • Fred, create some other project, give an npm install Axios --save and see if it makes the request... I went through the Ode here and I was able to get the data from the two Apis. var Axios = require('Axios'); Axios.get('http://fipeapi.appspot.com/api/1/carros/marcas.json') . then(res => { console.log(res.data); }) . catch(err => { console.log(err); }) Let cep = '89261765'; xios.get(http://viacep.com.br/ws/${cep}/json/) . then(result => { console.log(result.data); }) . catch(err => { console.log(err); })

  • In another project I received too. But not in this one. I think I know prq is happening this error when I try to connect the API. Includes a code block in the question, are the routes after authentication on the system, I am using JWT.

  • Try using the Chrome extension https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=pt-BR which allows Cors. That’s a matter of being local.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.