首页 > 解决方案 > 带有 CORS 的跨域 POST 请求返回 access-control-allow-origin 丢失

问题描述

我想执行从 localhost 到 localhost:81 的跨域请求,但我经常丢失 CORS-Header'Access-Control-Allow-Origin'。但我已经在 postHere.php 中设置了标题。我也试过 header('Access-Control-Allow-Origin: *'); 它也不起作用?

postHere.php

<?php
switch ($_SERVER['HTTP_ORIGIN']) {
    case 'http://localhost':
    case 'https://localhost':
        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
        header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
        header('Access-Control-Max-Age: 1000');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        break;
}

本地主机中的 HTML 文件,我想从中发送到本地主机:81

<html>
    <head>
        <script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
    </head>
    <body>
        <script>
            $.ajax({
            type: 'POST',
            url: 'http://localhost:81/postHere.php',
            crossDomain: true,
            data: '{"some":"json"}',
            dataType: 'json',
            success: function(responseData, textStatus, jqXHR) {
                var value = responseData.someKey;
            },
            error: function (responseData, textStatus, errorThrown) {
                alert('POST failed.');
            }
        });
    </script>
    </body>

</html>

标签: javascriptxmlhttprequestcorscross-domain

解决方案


您应该在第二个来源上启用您的服务器(在您的情况下localhost:81,尽管您可能应该使用8081)以允许跨域请求。检查 Mozilla 指南。

链接: https ://developer.mozilla.org/en-US/docs/Web/HTTP/CORS https://developer.mozilla.org/en-US/docs/Glossary/CORS


推荐阅读