3

I'm trying to do a post request of a server but keep getting a CORS error using axios and fetch in React.

the code:

fetch('https://api/entries', 
    { mode: 'no-cors',
      method: 'post',
      headers: {
        "Content-Type":"application/octet-stream",
        'Access-Control-Allow-Origin': true
      }, 
      body: JSON.stringify({
        "KEY":"VALUE"
      })
    })

  .then((response) => {
    console.log(response) 
  })
  .catch(err => console.log(err))

or


axios({
      method: 'post',
      url: 'https://api/entries',
      headers: {
        "Content-Type":"application/octet-stream",
        'Access-Control-Allow-Origin': true
      }, 
      data: {
            "KEY":"VALUE"

      }
    })
    .then(response => {

          console.log(response);
        })
    .catch(err => console.log(err));

axios console response

Access to XMLHttpRequest at 'https://api/entries' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

and the another

Fetch console response

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api/entries with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Thanks

Erdogan Oksuz
  • 621
  • 11
  • 17
Jorge pino
  • 31
  • 1
  • 1
  • 2
  • 1
    This is coming when the request from which the request is going and the server both are on a different domain. In that case from server side, you need to enable CORS so that you can do the request without any preflight error. – SatyaDash Apr 25 '19 at 09:55
  • checkout my answer here https://stackoverflow.com/a/55846380/2914407 it will solve your issue aswell – some_groceries Apr 25 '19 at 10:28

2 Answers2

18

The best and easiest way is to tackle this problem is to use Proxy URL.

Like so

const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';

axios.post(PROXY_URL+URL)
.then( i => console.log(i) )
.catch(e => console.error( "Error occured! ", e));

in your case try using this like this: This should work.

const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';
axios({
  method: 'post',
  url: PROXY_URL+URL, 
  data: {
        "KEY":"VALUE"
  }
})
.then(response => {

      console.log(response);
    })
.catch(err => console.log(err));

You can even use Proxy URL with fetch()

Zainul Abideen
  • 1,829
  • 15
  • 37
0

its depends on your backend for example, if you use Django you need to install https://github.com/ottoyiu/django-cors-headers and add this CORS_ORIGIN_ALLOW_ALL=True in setting file

OAH
  • 1,160
  • 2
  • 11
  • 24