php - 对预检请求的响应 - 不明白为什么?(CORS,获取,PHP)
问题描述
我在网上找到了很多关于这个的讨论,例如这个很好接受的答案,但仍然无法找出问题所在。我做了以下事情:
- 使用
create-react-app
. - 使用启动服务器
npm start
,可以在浏览器中看到我的应用程序。 - 用于
fetch
联系我的本地服务器:
fetch("http://xxx.xxx.xxx.xxx/endpoint.php", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
name: credentials.username,
password: credentials.password
})
}).then(response => {
console.log("fetch competed!");
});
- 在我的 PHP 端点中,
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
...
- 但随后 Chrome 控制台调试说:
CORS 策略已阻止从源“ http://xxx.xxx.xxx.xxx:3000 ”获取“ http://localhost:3000/endpoint.php ”的访问权限:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
完成一些阅读后,预检请求会向OPTIONS
服务器发送一个我在 PHP 标头中允许的请求。我还在文件中尝试了一些proxies
,package.json
并使用npm start
.
我也尝试过https://cors-anywhere.herokuapp.com/
,我仍然得到一个错误:
访问“ http://xxx.xxx.xxx.xxx:3000/php/login.php ”获取(重定向自“ https://cors-anywhere.herokuapp.com/http://xxx.xxx.xxx ” .xxx:3000/php/login.php ') 来自来源 ' http://xxx.xxx.xxx.xxx:3000 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否' Access-Control-Allow-Origin' 标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
我还尝试用fetch
更简单的东西替换我的:
fetch(url, {
method: "POST",
body: new URLSearchParams("email=test@example.com&password=pw")
});
但它仍然不起作用。
我不明白问题可能是什么?
解决方案
对于那些面临类似问题的人,我设法通过启动一个单独的 Apache 服务器来解决这个问题systemctl start apache
,并将我的 PHP 端点托管在 Apache 根目录中,例如/var/www/html/public/
. 由于某种原因,create-react-app
开发服务器无法正常工作,但将我的文件托管在单独的本地服务器上工作正常。
推荐阅读
- javascript - 令牌,无效的签名密钥
- python - 在 window.__INITIAL_STATE__ 中找不到属性,尽管它存在
- php - OpenCart - 无法更新管理仪表板
- angular7 - 是否可以针对两种不同的搜索条件(例如,医院和车库)进行谷歌地图搜索?
- keyboard-shortcuts - 什么是mac中删除光标留下的文本直到终端行开头的快捷方式
- angular-material - @angular 材质主题无法在浏览器上加载
- c# - 在门户中编写的 Azure 函数中包含 NuGet 包
- kubernetes - Kubernetes 大小考虑
- autoencoder - 为什么 VAE 的解码器可以使用正态分布样本生成合理的输出?
- python - 使用model.fit时如何将'training'参数传递给tf,keras.Model