React和PHP - CORS错误:MissingAllowOriginHeader

kmynzznz  于 2023-09-29  发布在  PHP
关注(0)|答案(1)|浏览(170)

我正在开发一个todo应用程序,第一次使用React和PHP。使用Apache(XAMPP)。
App.js:

import { useEffect, useState } from "react";

const App = () => {
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    fetch(`${process.env.REACT_APP_ENDPOINT}`, {
      method: "POST",
      body: JSON.stringify({
        action: "todos",
      }),
    })
      .then((response) => response.json())
      .then((data) => setTodos(data));
  }, []);
  return (
    <div>
      <h1>Todo App</h1>
    </div>
  );
};

export default App;

index.php:

<?php
header('Access-Control-Allow-Origin: *');

try {
    $db = new PDO("mysql:host=localhost;dbname=todo", "mustafa", "12345");
} catch (PDOException $e) {
    die($e->getMessage());
}

$action = $_POST['action'];

switch ($action) {
    case 'todos':
        $query = $db->query("SELECT * FROM todos order by id desc")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($query);
        break;
}

虽然我有header('Access-Control-Allow-Origin: *'),但它会抛出MissingAllowOriginHeader错误:
CORS策略已阻止从源“http://localhost:3000”访问“http://localhost/react-php-backend”的获取:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果一个不透明的响应满足了你的需求,将请求的模式设置为“no-cors”,以在禁用CORS的情况下获取资源。
给出这个错误的原因是什么?我该怎么办?因此,我无法连接数据库。

w8ntj3qf

w8ntj3qf1#

在2023年,当几乎所有的浏览器都需要严格的来源策略时,您需要修改您的标头,无论是在.htaccess中

<IfModule mod_headers.c>
   #Header set Access-Control-Allow-Origin "*"
   SetEnvIf Origin "http(s)?://(.+\.)?domain\.ext(:\d{1,5})?$" CORS=$0
   Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
   Header merge  Vary "Origin"
   Header set Access-Control-Allow-Methods "GET, POST, PATCH, PUT, DELETE, OPTIONS"
   Header set Access-Control-Allow-Headers: "*"
   
</IfModule>

在PHP内部

<?php
function cors()
{
    // for options, return imm.
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        // may also be using PUT, PATCH, HEAD etc
        {
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        }

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
        }

        exit(0);
    }

    $origin = "*";
    if (isset($_REQUEST['origin'])) {
        $origin = $_REQUEST['origin'];
    }

    if (isset($_SERVER['origin'])) {
        $origin = $_SERVER['origin'];
    }

    if (isset($_SERVER['HTTP_REFERER'])) {
        $origin = $_SERVER['HTTP_REFERER'];
    }

    if (isset($_SERVER['HTTP_ORIGIN'])) {
        $origin = $_SERVER["HTTP_ORIGIN"];
    }

    // remove trailing / for origin
    $origin = rtrim($origin, "/");

    header("Access-Control-Allow-Origin: " . $origin, true);
    header("Access-Control-Allow-Headers: *", true);
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get', true);
    header('Access-Control-Allow-Credentials: true', true);
}

cors();

tbh,两个都可以……

相关问题