【问题标题】:CORS issue on php built apiphp构建的api上的CORS问题
【发布时间】:2021-12-14 12:45:00
【问题描述】:

我已经构建了 php api 来交换数据,但这会导致我的 web 应用程序出现 CORS 问题。 它会根据邮递员的请求返回正确的数据,但不会在 Web 应用程序上返回。

我尝试在后端添加以下代码

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();
}


开发者工具中的Network标签如下。

请求选项卡和响应选项卡什么也不显示。


以前我在本地测试服务器上运行过它。我将 php 文件上传到我的 AWS 服务器上,它工作正常。

【问题讨论】:

  • 看来主要是您实际上遇到了网络错误,但如果我们能看到您的 axios 代码和错误处理代码,这会很有帮助。
  • 你能分享你的 xhr 请求吗?
  • edit your question 包含您想与我们分享的任何代码,并使用formatting tools 以确保其清晰呈现。正如您自己所看到的,在 cmets 中很难阅读。谢谢。
  • P.S.您是否从所有这些尝试中得到完全相同的错误?还是每次都不一样?这将有助于完全清楚。
  • 你使用的是像 Laravel 这样的框架还是核心 php?和版本?

标签: php ajax cors


【解决方案1】:

尝试使用凭据发送您的 XHR 请求?

axios.get('your api url', {withCredentials: true});

withCredentials() 使您的浏览器在您的 XHR 请求中包含 cookie 和身份验证标头。如果您的服务依赖于 cookie(包括会话 cookie),则只能使用此选项。

【讨论】:

  • 我试过你的建议,但它给了我同样的错误。我也尝试添加“crossdomain:true”但没有工作。
  • @Young-KwangOh 好的。在这方面还会想到什么。你能先删除你的cookies吗?您的前端与您的 api 服务器在同一个域或子域上吗?
  • 是的。目前这两个文件都在我的本地测试服务器上运行。
  • @ADyson 谢谢你的建议。顶!
  • 我已经解决了这个问题。谢谢你帮助我
【解决方案2】:

您的Origin 似乎与请求目标的主机名和端口相同,只是协议不同(HTTP 与 HTTPS)。

因此,如果您通过 HTTPS 访问您的页面(就像您尝试通过 HTTPS 访问 AJAX 请求一样),或者通过 HTTP 访问 AJAX(就像您的页面)。

一旦主页面和 AJAX URL 的协议、主机名/域和端口相同,它们就会被视为“同源”,因此 CORS (Cross-Origin Resource Sharing) 限制不适用。

【讨论】:

  • 以前我在本地测试服务器上运行过它。我将 php 文件上传到我的 AWS 服务器上,它可以工作。天哪……谢谢你帮助我。
猜你喜欢
  • 2019-08-28
  • 2021-09-19
  • 2018-05-23
  • 2016-12-15
  • 2017-07-26
  • 2020-03-18
  • 2021-11-22
  • 2020-07-21
  • 1970-01-01
相关资源
最近更新 更多