当我可以从 PHP 发出请求时,为什么 Ajax 会给我一个跨源错误?

2022-01-04 00:00:00 get jquery php javascript ajax

我可以从 PHP 发出 GET 请求并获得正确的响应.这是我使用的功能:

PHP

function httpGet($url){$ch = curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_HEADER, false);$output=curl_exec($ch);curl_close($ch);返回 $output;}

一个简单的例子:

$fakevalue='iamfake';$url="http://fakeurl.com?fakeparameter=".$fakevalue;$jsondata= httpGet($url);$fake_array = json_decode($jsondata, true);$weed_var=$fake_array['杂草'];//成功获得杂草.

该函数返回来自服务器的响应.

现在我在 AJAX 中尝试相同的 HTTP GET 请求,但我无法得到响应.

最初我认为问题出在我使用的 JavaScript 函数上.Google 为我提供了许多用于执行 HTTP GET 请求的 JavaScript 函数,但它们都有相同的问题.请求返回一个错误,而不是我在使用 PHP 时得到的数据.

JAVASCRIPT

var fakevalue = "iamfake";var fake_data = {假参数:假值};$.ajax({网址:http://fakeurl.com",数据:fake_data,类型:获取",跨域:真,数据类型:json",成功:功能(一){$("#getcentre").html(a);},错误:函数(){alert("失败了!");}});

JavaScript 错误

<块引用>

XMLHttpRequest 无法加载 http://fakeurl.com?fakeparameter=fakevalue.请求的资源上不存在Access-Control-Allow-Origin"标头.因此,不允许访问源http://localhost".`

我知道你会告诉我使用 CORS,但如果是因为没有Access-Control-Allow-Origin"标头,那么我如何在 PHP 中获得相同服务的响应?

解决方案

使用 PHP(或在您的服务器上运行的任何其他应用程序,或独立应用程序(包括作为浏览器扩展安装的应用程序)),您 正在使用您的凭据(您的 cookie、您的 IP 地址、您的其他一切)从 Bob 的服务器请求数据.

使用 Ajax,您要求 Alice 的浏览器使用 她的 凭据从 Bob 的服务器请求数据,然后将该数据提供给您的JavaScript(然后可以将其发送回您的服务器,以便您自己查看).

Bob 可能会给 Alice 提供不同的数据,然后他会给你.例如:Bob 可能正在运行 Alice 的电子银行系统或公司内部网.

因此,除非 Bob 的服务器告诉 Alice 的浏览器可以向您提供该数据(使用 CORS),否则浏览器将阻止您的 JavaScript 访问该数据.

有 CORS 的替代方案,但它们涉及使用并非设计为数据格式 (JSONP) 的文件类型分发数据(这也需要 Bob 的服务器合作)或让您的服务器从Bob,然后通过您服务器上的 URL(或像 YQL 那样两者的某种组合)使其可用(这意味着您获得的是 Bob 将提供给您的数据,而不是 Bob 将提供给 Alice 的数据).

I can make a GET request from PHP and get the correct response. This is the function I use:

PHP

function httpGet($url)
{
    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);

    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}

A simple example:

$fakevalue='iamfake';
$url="http://fakeurl.com?fakeparameter=".$fakevalue;
$jsondata= httpGet($url);
$fake_array = json_decode($jsondata, true);
$weed_var=$fake_array['weeds']; // successfully obtained weed.

This function returns the response from the server.

Now I am trying the same HTTP GET request in AJAX, but I can't get the response.

Initially I thought the problem was with the JavaScript function that I use. Google provided with me lots of JavaScript functions for performing the HTTP GET request but they all had the same problem. The request returns an error instead of the data that I got when I used PHP.

JAVASCRIPT

var fakevalue = "iamfake";

var fake_data = {
    fakeparameter: fakevalue
};

$.ajax({
    url: "http://fakeurl.com",
    data: fake_data,
    type: "GET",
    crossDomain: true,
    dataType: "json",
    success: function(a) {
        $("#getcentre").html(a);
    },
    error: function() {
        alert("Failed!");
    }
});

Error from JavaScript

XMLHttpRequest cannot load http://fakeurl.com?fakeparameter=fakevalue. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.`

I know you are going to tell me to use CORS, but if it was because of the absence of 'Access-Control-Allow-Origin' header, then how did I get response for the same service in PHP?

解决方案

With PHP (or anything else running on your server, or a standalone application (including those installed as a browser extension)), you are requesting data from Bob's server using your credentials (your cookies, your IP address, your everything else).

With Ajax, you are asking Alice's browser to request data from Bob's server using her credentials and then to make that data available to your JavaScript (which can then send it back to your server so you can see it yourself).

Bob might give different data to Alice then he would give to you. For example: Bob might be running Alice's eBanking system or company intranet.

Consequently, unless Bob's server tells Alice's browser that it is OK to make that data available to you (with CORS), the browser will prevent your JavaScript from accessing that data.

There are alternatives to CORS, but they involve either distributing the data using a file type that isn't designed to be a data format (JSONP) (which also requires Bob's server to cooperate) or having your server fetch the data from Bob and then make it available through a URL on your server (or some combination of the two like YQL does) (which means that you get the data Bob will give to you and not the data Bob will give to Alice).

相关文章