【发布时间】:2021-12-05 18:12:03
【问题描述】:
我想执行从 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>
【问题讨论】:
标签: javascript xmlhttprequest cors cross-domain