gpt4 book ai didi

javascript - 如何发起一个简单的 CORS 请求?

转载 作者:可可西里 更新时间:2023-11-01 16:55:55 24 4
gpt4 key购买 nike

情况:

我正在使用 AngularJs 制作应用程序。我需要发出 CORS 请求以从不同地址上的 api 获取数据。

在 api 上我输出一个非常简单的 json,用于测试目的:

[{"id":0,"name":"First"},{"id":1,"name":"Second"},{"id":2,"name":"Third"}]

我需要获取这些数据并显示在我的应用中。

$HTTP 调用:

进行 $http 调用时出现以下错误,因为 api 位于不同的域中:

No 'Access-Control-Allow-Origin' header is present on the requested resource

CORS 请求 - 代码:

// Create the XHR object.
$scope.createCORSRequest = function(method, url)
{
var xhr = new XMLHttpRequest();

if ("withCredentials" in xhr)
{
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined")
{
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else
{
// CORS not supported.
xhr = null;
}

return xhr;
}


// Helper method to parse the title tag from the response.
$scope.getTitle = function(text)
{
return text.match('<title>(.*)?</title>')[1];
}


// Make the actual CORS request.
$scope.makeCorsRequest = function()
{
var url = 'http://DOMAIN.COM/main/json_export_test';

var xhr = $scope.createCORSRequest('GET', url);

console.log('----- xhr -----');
console.log(xhr);

if (!xhr)
{
alert('CORS not supported');
return;
}

// Response handlers.
xhr.onload = function()
{
var text = xhr.responseText;
var title = $scope.getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};

xhr.onerror = function()
{
alert('Woops, there was an error making the request.');
};

xhr.send();
}

当我运行函数 makeCorsRequest 时,我收到 xhr.onerror 调用的警报

但我不知道为什么它不起作用。

API:

这是 api 中非常简单的 php 函数,用于测试目的:

public function json_export_test()
{
$data = array(
array(
"id" => 0,
"name" => "First"
),
array(
"id" => 1,
"name" => "Second"
),
array(
"id" => 2,
"name" => "Third"
)
);

echo json_encode($data);
}

问题:

如何发出简单的 CORS 请求?

编辑 - 解决方案:

修改后的api是这样的,感谢回复:

public function json_export_test()
{
header('Access-Control-Allow-Origin: *');

$data = array(
array(
"id" => 0,
"name" => "First"
),
array(
"id" => 1,
"name" => "Second"
),
array(
"id" => 2,
"name" => "Third"
)
);

echo json_encode($data);
}

最佳答案

一般来说:您只需使用 XMLHttpRequest 发出一个普通请求。浏览器将处理其余部分。 (不支持 CORS 或要求您使用 XDomainRequest 而不是 XMLHttpRequest 的旧浏览器除外——但您似乎已经考虑到了这一点)。

您收到的错误消息表明您没有收到 CORS 响应,因此浏览器无权将其他网站的数据提供给您的 JavaScript。

您需要在对跨源请求的 HTTP 响应 中包含 Access-Control-Allow-Origin: *(或更具体的内容)。

关于javascript - 如何发起一个简单的 CORS 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31068754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com