访问控制源在Chrome中使用Reios Web抛​​出错误中的Axios时出现标题错误 [英] Access Control Origin Header error using Axios in React Web throwing error in Chrome

查看:119
本文介绍了访问控制源在Chrome中使用Reios Web抛​​出错误中的Axios时出现标题错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React Web应用程序中的Axios进行API调用。但是我在Chrome中收到错误,


XMLHttpRequest无法加载 https://example.restdb.io/rest/mock-data 。请求的资源上不存在Access-Control-Allow-Origin标头。因此,不允许访问 http:// localhost:8080




  {
axios.get('https://example.restdb.io/rest/mock-data', {
标题:{
'x-apikey':'API_KEY',
},
responseType:'json',
})。then(response => {
this.setState({tableData:response.data});
});
}

我还在StackOverflow上读到了几个关于同一问题的答案,标题为Access -Control-Allow-Origin但仍然想知道如何解决这个问题。我不想使用扩展程序IN Chrome或使用临时黑客来解决这个问题。请提出解决上述问题的标准方法。



在尝试了几个答案之后我尝试了这个,

 标题:{
'x-apikey':'59a7ad19f5a9fa0808f11931',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},

现在我收到错误,


请求标题字段Access-Control-Allow-Origin不是在预检响应中由Access-Control-Allow-Headers允许



解决方案

如果你的后端支持CORS ,您可能需要在此请求中添加此标头:

  headers:{Access-Control-Allow-Origin: *} 

如果不是 - 您必须确保服务器可以管理CORS请求。



您可以找到有关此机制的文档re:
https://developer.mozilla.org/en -US / docs / Web / HTTP / Access_control_CORS


Im making an API call using Axios in a React Web app. However Im getting the error in Chrome as,

XMLHttpRequest cannot load https://example.restdb.io/rest/mock-data. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

    {
      axios.get('https://example.restdb.io/rest/mock-data', {
      headers: { 
      'x-apikey': 'API_KEY',
      },
    responseType: 'json',
     }).then(response => {
      this.setState({ tableData: response.data });
    });
    }

I have also read several answers on StackOverflow about the same issue, titled "Access-Control-Allow-Origin" but still coudnt figure out how to solve this. I dont want to use an extension IN Chrome or use a temporary hack to solve this. Please suggest the standard way of solving the above issue.

After trying out few answers I have tried with this,

    headers: { 
      'x-apikey': '59a7ad19f5a9fa0808f11931',
      'Access-Control-Allow-Origin' : '*',
      'Access-Control-Allow-Methods' : 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
    },

Now I get the error as,

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response

解决方案

If your backend support CORS, you probably need to add to your request this header:

headers: {"Access-Control-Allow-Origin": "*"}

If not - you must ensure the server can manage the CORS-requests.

You can find documentation about this mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

这篇关于访问控制源在Chrome中使用Reios Web抛​​出错误中的Axios时出现标题错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆