[英]CORS issue on php built api
我已经构建了 php api 来交换数据,但它会导致我的 Web 应用程序出现 CORS 问题。 它在邮递员请求上返回正确的数据,但不在网络应用程序上返回。
我尝试在后端添加以下代码
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Credentials: true");
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');
但它给了我同样的错误信息。
以下是邮递员回复的标题。
标头包含邮递员响应中的 CORS 设置,但仍然无法正常工作。 有没有其他方法可以修复它?
我尝试了几种请求数据的方法
1.
axios.get("localhost:1234/getSingersJson.php?test=[144]")
var url = "localhost:1234/getSingersJson.php";
var params = "[144]";
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function(){
console.log(this.responseText);
}
xmlhttp.open("GET", url + "?test=" + params);
xmlhttp.send();
fetch(url + "?test=" + params)
.then(response => {
if(!response.ok) {
throw Error(response.statusText);
}
console.log(response)
})
每个代码的确切错误消息如下所示。
function api_test(){
var url = "https://localhost:1234/getSingersJson.php";
var params = "[144]";
fetch(url + "?test=" + params)
.then(response => {
if(!response.ok) {
throw Error(response.statusText);
}
console.log(response)
})
}
function api_test(){
var url = "https://localhost:1234/getSingersJson.php";
var params = "[144]";
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function(){
console.log(this.responseText);
}
xmlhttp.open("GET", url + "?test=" + params);
xmlhttp.send();
}
开发者工具中的网络选项卡如下。
请求选项卡和响应选项卡什么也不显示。
以前我在我的本地测试服务器上运行它。 我在我的 AWS 服务器上上传了 php 文件,它工作正常。
您的Origin
似乎与请求目的地具有相同的主机名和端口,只是协议不同(HTTP 与 HTTPS)。
因此,如果您通过 HTTPS 访问您的页面(就像您尝试通过 HTTPS 访问 AJAX 请求一样),或者通过 HTTP 访问 AJAX(就像您的页面一样),那么这个请求实际上根本不需要受 CORS 的约束.
一旦主页和 AJAX URL 的协议、主机名/域和端口相同,它们就被认为是“同源”,因此CORS(跨源资源共享)限制不适用。
尝试使用凭据发送您的 XHR 请求?
axios.get('your api url', {withCredentials: true});
withCredentials() 使您的浏览器在您的 XHR 请求中包含 cookie 和身份验证标头。 如果您的服务依赖于 cookie(包括会话 cookie),则它只能使用此选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.