带CORS的跨域POST请求返回access-control-allow-origin缺失



我想执行从localhost到localhost:81的跨域请求,但我不断得到CORS-Header' access - control - allow - origin '丢失。但是我已经在postthere。php中设置了header。我也试过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;
}

我想发送到localhost的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>

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

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

最新更新