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

标签 javascript angularjs http cors ionic-framework

情况:

我正在使用 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/

相关文章:

javascript - 如何向 webpacker 添加库以在 Stimulus JS Controller 中使用

javascript - 如何有条件地将列更改为 AngularJS 网格中的文本框?

javascript - 使用模态窗口实例在 Angular JS 中保存并下一步

http - 如何使用 netcat 手动发出 HTTP GET 请求?

javascript - 在 Angular 闭包内引用服务属性/方法的最合适方法是什么?

javascript - 当 PHP 代码开始运行时弹出 Javascript 警报,并在执行完成时弹出警报

javascript - 查看字符串结尾是否匹配

javascript - Angular 和 Jasmine - $scope 函数未定义

html - 如何在没有 JavaScript 的情况下清除已经发送到浏览器的 HTML 内容?

c# - 。网。异步 HttpWebRequest 的最大数量