由于CORS问题来自本地主机,请求失败

我在SO和不同的博客上都看到了数十个问题,这些问题都用“答案”来讨论-都无济于事。

我的本地机器(Ubuntu 16.04)上有一个React.js应用程序。在本地,我尝试通过运行npm

start对其进行测试,然后它将浏览器打开到http:// localhost:3000。

在一页上,我试图访问共享托管服务器上的PHP api。

Chrome和Firefox都说由于服务器没有失败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服务器入口点上,我确实有:

header("Access-Control-Allow-Orgin: *");

header("Access-Control-Allow-Methods: *");

这是我在react应用中进行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});

})

}

}

我已经在Chrome和Firefox上进行过尝试;我还尝试将服务器别名从本地主机移开。我已经尝试过这种no-cors方法,但确实可以访问我-

但会破坏所有内容。我尝试了是否在没有fetch请求的情况下传递标头。

我确实通过安装此Chrome插件使其工作。我觉得这是一种解决方法,想知道这里是否有编码答案。

回答:

我是个白痴。

Origin被拼写为Orgin

这种错字在我的项目中已经存在了将近三年。这是我第一次需要使用跨域访问。

以上是 由于CORS问题来自本地主机,请求失败 的全部内容, 来源链接: utcz.com/qa/436108.html

回到顶部