最佳答案
我在一个 React Web 应用程序中使用 Axios 进行 API 调用,然而,我在 Chrome 中得到了这个错误:
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 });
});
}
我也阅读了关于 Stack Overflow 的几个答案,都是关于同一个问题的,题目是 Access-Control-Allow-Origin
,但仍然不知道如何解决这个问题。我不想在 Chrome 中使用扩展或者使用临时黑客技术来解决这个问题。请提出解决上述问题的标准方法。
在尝试了几个我试过的答案之后,
headers: {
'x-apikey': '59a7ad19f5a9fa0808f11931',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},
现在我得到的错误是,
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response