已通过使用axios和Fetch in react被CORS策略阻止

时间:2019-04-25 09:50:13

标签: xmlhttprequest axios fetch

我正在尝试对服务器进行发布请求,但是使用axios并在React中获取消息时,会不断出现CORS错误。

代码:

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


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控制台响应

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.

和另一个

获取控制台响应

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.

谢谢

2 个答案:

答案 0 :(得分:1)

解决此问题的最佳和最简便的方法是使用代理URL

喜欢

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

在您的情况下,请尝试使用这种方式:这应该可行。

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

您甚至可以将代理URL与fetch()一起使用

答案 1 :(得分:0)

取决于您的后端 例如,如果您使用Django 您需要安装https://github.com/ottoyiu/django-cors-headers 并在设置文件中添加此CORS_ORIGIN_ALLOW_ALL = True