问题描述
我已经看到了SO上的几十个问题,不同的博客用答案来讨论这个问题 - 一切都没有用。
I have seen dozens of questions on SO and different blogs talking about this with "answers" -- all to no avail.
我有一个React.js应用程序在我的本地机器上(Ubuntu 16.04)。在本地,我尝试通过运行 npm start
来测试它,然后打开浏览器。
I have a React.js app on my local machine (Ubuntu 16.04). Locally, I try to test it by running npm start
and it opens up the browser to http://localhost:3000.
在一个页面上,我正在尝试访问我的共享托管服务器上的PHP api。
On one page, I am trying to access my PHP api which is on my shared hosting server.
Chrome和Firefox都说由于服务器没有 Access-Control-Allow-Orgin
而失败。
Chrome and Firefox both say that it fails due to server not having Access-Control-Allow-Orgin
.
确切消息:
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
但是,在我的php服务器入口点,我有:
However, upon my php server entry point I do have:
header("Access-Control-Allow-Orgin: *");
header("Access-Control-Allow-Methods: *");
这是我在我的反馈应用程序中进行api调用的地方:
Here is where I make my api call in my react app:
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});
})
}
}
我在Chrome和Firefox上都试过了这个;我也尝试将我的服务器别名为localhost。我已经尝试过 no-cors
方法,它可以让我访问 - 但当然会打破一切。我已尝试使用和不传递标题以及我的 fetch
请求。
I have tried this on both Chrome and Firefox; I have also tried to alias my server away from localhost. I have tried the no-cors
approach, which does get me access -- but breaks everything of course. I have tried with and without passing headers along with my fetch
request.
更新 :
我确实安装了。我觉得这是一种解决方法,想知道这里是否有编码答案。
I did get it to work by installing this Chrome plugin. I feel this is a workaround and would like to know if there is a coding answer here.
推荐答案
我是个白痴。
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.
这篇关于由于来自localhost的来源的CORS问题,请求失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!