Problem with CORS in React application

0

I have an application that makes a request for a JSON via axios. Follow the function

axios.get("http://localhost/teste.json")
  .then((res) => {
    this.setState({value: res.data.tgt.screenPosX})
  }).catch((err) => {
    console.log('Error')
})

But as the development server is running in 3000 I can not access this json on the apache server due to CORS policy

Requisição cross-origin bloqueada: A política de mesma origem (Same Origin Policy) impede a leitura do recurso remoto em http://localhost/teste.json. (Motivo: o cabeçalho CORS 'Access-Control-Allow-Origin' não está presente).

How can I solve this problem? How do I consume this JSON without going through CORS?

I do not know much about backend, but I need to solve the problem yesterday.

Thank you in advance !!

    
asked by anonymous 10.09.2018 / 20:44

1 answer

0

Problem solved. I added a .htaccess on my apache server allowing CORS. Remembering that I'm just using it for development, it's probably not a safe alternative.

Follow the added content in .htaccess

RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [L,R=204]

Header set X-Content-Type-Options "nosniff"
Header set X-XSS-Protection "1; mode=block"
   # Always set these headers for CORS.
Header always set Access-Control-Max-Age 1728000
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header always set Access-Control-Allow-Headers: "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,C$
Header always set Access-Control-Allow-Credentials true
    
10.09.2018 / 22:28