【发布时间】: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?和版本?