代码之家  ›  专栏  ›  技术社区  ›  Mohammad Massri

跨来源请求在PHP和JavaScript中被阻止

  •  0
  • Mohammad Massri  · 技术社区  · 3 年前

    我试图向这个php代码发送一个使用javascript的post请求,但我收到了以下错误:

    阻止跨来源请求:同源策略不允许读取“我的web应用程序的url”处的远程资源。(原因:CORS请求未成功)。状态代码:(null)。

    这是我的js代码:

    const url = 'https://opecart9349.000webhostapp.com/unzipper/opencart/index.php?route=customapi/test';
    
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then(response => response.json())
      .then(data => {
        // Handle the response data
        console.log(data);
      })
      .catch(error => {
        // Handle any errors
        console.error('Error:', error);
      });
    

    这是我的php代码:

    <?php
    class ControllerCustomapiTest extends Controller {
        public function index() {
            
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
            header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
            
            header('Content-Type: application/json');
    
            $response = array('success' => true);
    
            echo json_encode($response);
        }
    }
    ?>
    
    0 回复  |  直到 3 年前
        1
  •  1
  •   Selcuk Mollaibrahimoğlu    3 年前

    访问控制允许来源:并非所有浏览器都支持*值。在*字段中,输入您发送请求的域名。

    也可以!对于选项类型请求!你必须发送答案。

    if (isset($_SERVER['HTTP_REFERER'])) {
        // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
        // you want to allow, and if so:
        header("Access-Control-Allow-Origin: http://localhost:4200");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH, OPTIONS");
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
        die('OK!');
    }