javascript - 带有 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>
解决方案
您应该在第二个来源上启用您的服务器(在您的情况下localhost:81
,尽管您可能应该使用8081
)以允许跨域请求。检查 Mozilla 指南。
链接: https ://developer.mozilla.org/en-US/docs/Web/HTTP/CORS https://developer.mozilla.org/en-US/docs/Glossary/CORS
推荐阅读
- javascript - 使用 redux 钩子时使用 redux 操作的最佳选择是什么?
- sql - Impala 2.11:AnalysisException:选择列表中不支持子查询
- swift - 在 SwiftUI 中获取当前的经纬度
- c++ - 是否可以禁止一个类被动态转换为?
- git - Git - 将发布分支合并到主分支
- tensorflow - 任何想法如何解决激活函数的问题?
- nativescript - 在 nativescript 中的中继器中向布局添加类似列表视图/按钮的样式行为
- apache-nifi - HandleHttpProcessor 是否支持“CORS”(Access-Control-Allow-Origin)
- sql - INSERT (values) INTO 两个具有外键关系的表
- scala - 在 for-comp 中使用 EitherT-s 进行数据验证