-1

enter image description here

import axios from "axios"

export function App() {
  const config = {
    headers: { Authorization: `Bearer TOKEN` },
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET",
    'Access-Control-Allow-Headers': '*',
    "Access-Control-Allow-Credentials":  "true",
    "Access-Control-Expose-Headers": "*",
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Origin": "*",
  };


  axios.get(
    "https://URL",
    config
  )
    .then(console.log)
    .catch(console.log);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Access to XMLHttpRequest at 'https://URL' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've got problem with getting data from API using axios. It is blocked by CORS policy, I know that I use extension to website, but I am not allowed to use it. TOKEN and URL are hidden.

*Problem is only when I try to send request with axios, with http/curl it works. Also it's working while I am using CORS extension at Chrome

THAT SOLUTION WORKED FOR ME:

https://www.youtube.com/watch?v=4B5WgTiKIOY

Ewaastw
  • 1
  • 2
  • 1
    This has nothing to do with React, and is likely something you need to configure with matching settings in both frontend and backend. Also note, that sometimes a CORS error is thrown for an issue that _isn't actually related to CORS_. – paddotk Aug 24 '22 at 12:28

1 Answers1

-1

I had similiar issue and used the following header options (note that I use fetch, but axios is similiar):

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append('Accept', 'application/json');
myHeaders.append("Authorization", "Bearer "+getCookie('token'));
var requestOptions = {
    headers: myHeaders,
    method: 'GET',
    redirect: 'follow',
    credentials: 'include'
  };

Also, you are very likely to get CORS error because request are coming from your adress (probably something like yourIP:3000). You can either ask your backend developer to allow requests from your origin (for development) or try to send requests from an allowed dns.

You can also get opaque response with "no-cors" header, however it may not be sufficient for you