has been blocked by CORS policy by using axios and

2019-08-01 19:27发布

问题:

This question already has an answer here:

  • Axios having CORS issue 2 answers

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

回答1:

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()



回答2:

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