首页 > 解决方案 > 对预检请求的响应 - 不明白为什么?(CORS,获取,PHP)

问题描述

我在网上找到了很多关于这个的讨论,例如这个很好接受的答案,但仍然无法找出问题所在。我做了以下事情:

  1. 使用create-react-app.
  2. 使用启动服务器npm start,可以在浏览器中看到我的应用程序。
  3. 用于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!");
    });
  1. 在我的 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");

    ...
  1. 但随后 Chrome 控制台调试说:

CORS 策略已阻止从源“ http://xxx.xxx.xxx.xxx:3000 ”获取“ http://localhost:3000/endpoint.php ”的访问权限:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

完成一些阅读后,预检请求会向OPTIONS服务器发送一个我在 PHP 标头中允许的请求。我还在文件中尝试了一些proxiespackage.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")
    });

但它仍然不起作用。

我不明白问题可能是什么?

标签: phpcorsfetchcreate-react-app

解决方案


对于那些面临类似问题的人,我设法通过启动一个单独的 Apache 服务器来解决这个问题systemctl start apache,并将我的 PHP 端点托管在 Apache 根目录中,例如/var/www/html/public/. 由于某种原因,create-react-app开发服务器无法正常工作,但将我的文件托管在单独的本地服务器上工作正常。


推荐阅读