Problem with CORS in React application

Asked

Viewed 1,776 times

1

I have an application that requests a JSON via Xios. It follows 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 on 3000 I cannot access this json on 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 don’t know much about backend but I need to solve the problem yesterday.

Thanks in advance!!

  • 1

    Are you requesting a server you developed ? if yes, you can change the application’s CORS to accept requests for any domain.

  • I didn’t exactly develop it, but it’s local and I have access to it. How can I do this, I have to allow the server in localhost to accept requests?

  • 2

    What language are you using in the Back-End? You have to set up Cors in your Back End!

  • The backend ta in php, I will try to work on this and give feedback to you

1 answer

1

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

Follow the content added 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
  • if your API is not public has another safer way to resolve this, example sending a header together in the request of the frontend to API.

  • anything depending on your answer I put here a possible solution.

Browser other questions tagged

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