[英]Request fails due to CORS issue with origin from localhost
I have seen dozens of questions on SO and different blogs talking about this with "answers" -- all to no avail. 我已经看到了SO上的几十个问题,不同的博客用“答案”来讨论这个问题 - 一切都无济于事。
I have a React.js app on my local machine (Ubuntu 16.04). 我在本地计算机上有一个React.js应用程序(Ubuntu 16.04)。 Locally, I try to test it by running npm start
and it opens up the browser to http://localhost:3000 . 在本地,我尝试通过运行npm start
来测试它,然后打开浏览器到http:// localhost:3000 。
On one page, I am trying to access my PHP api which is on my shared hosting server. 在一个页面上,我试图访问我的共享托管服务器上的PHP api。
Chrome and Firefox both say that it fails due to server not having Access-Control-Allow-Orgin
. Chrome和Firefox都说它因服务器没有Access-Control-Allow-Orgin
而失败。
Exact Message: 确切消息:
Failed to load http://---/api/v1/categories: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost.com:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
localhost.com/:1 Uncaught (in promise) TypeError: Failed to fetch
However, upon my php server entry point I do have: 但是,在我的php服务器入口点我有:
header("Access-Control-Allow-Orgin: *");
header("Access-Control-Allow-Methods: *");
Here is where I make my api call in my react app: 这是我在我的反应应用程序中进行api调用的地方:
componentDidMount() {
var options = {
method: 'get',
headers: {
"Access-Control-Request-Headers": "*",
"Access-Control-Request-Method": "*"
},
}
// I have since removed the headers from the options as advised in the comments
fetch('http://---/api/v1/categories', options)
.then(results => {
return results.json();
}).then(data => {
let categories = data.map((category) => {
return(
// edited out
)
})
this.setState({categories: categories});
})
}
}
I have tried this on both Chrome and Firefox; 我在Chrome和Firefox上都试过这个; I have also tried to alias my server away from localhost. 我也尝试将我的服务器别名为localhost。 I have tried the no-cors
approach, which does get me access -- but breaks everything of course. 我尝试了no-cors
方法,这让我可以访问 - 但当然会打破一切。 I have tried with and without passing headers along with my fetch
request. 我已尝试使用和不传递标题以及我的fetch
请求。
UPDATE : 更新 :
I did get it to work by installing this Chrome plugin . 我确实通过安装此Chrome插件来实现它 。 I feel this is a workaround and would like to know if there is a coding answer here. 我觉得这是一种解决方法,想知道这里是否有编码答案。
I'm an idiot. 我是个白痴。
Origin
was misspelled as Orgin
. Origin
被拼错为Orgin
。
This typo has existed in my project for almost three years. 这个错字已经存在于我的项目中近三年了。 This was the first time I needed to use cross-domain access. 这是我第一次使用跨域访问。
header("Access-Control-Allow-Methods: *");
Should be: 应该:
header("Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS, PUT, DELETE, PATCH");
...and any other methods you intend to accept. ......以及您打算接受的任何其他方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.