我在尝试将 POST 与我的 API 一起使用时遇到 CORS 问题。 CORS 策略已阻止从源“null”访问“http://localhost/finalMandatory/api/track/create.php”处的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:它没有 HTTP正常状态。
我尝试关注其他一些似乎有相同问题的帖子,但我很难在自己的代码中实现它。
$.ajax({
url: "http://localhost/finalMandatory/api/track/create.php",
type : "POST",
contentType : 'application/json',
data : form_data,
success : function(result) {
showProducts();
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
console.log(form_data);
}
});
我也在我的 api 中使用这些标头,我认为这足以处理 CORS 问题。
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
我希望有人能帮我解决我的问题。
答案 0 :(得分:2)
我猜发送到 create.php 的 OPTION 请求失败了。可能是因为您的后端代码即使在这种情况下也试图执行该操作。 OPTION 请求应仅以 CORS 标头和空正文终止。您可以使用 REST 客户端(例如 Postman)进行检查。