使用JavaScript绕过CORS进行远程JSON请求

时间:2019-05-24 11:58:29

标签: javascript json cors

有没有一种方法可以从URL中访问API,而无需Chrome扩展CORS(Allow-Control-Allow-Origin)? 该代码仅在扩展名打开的情况下起作用。 我无权访问远程服务器。

var getJSON = function(url, callback) {

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';

    xhr.onload = function() {

        var status = xhr.status;

        if (status == 200) {
            callback(null, xhr.response);
        } else {
            callback(status);
        }
    };

    xhr.send();
    };

    getJSON('http://faust.izor.hr/autodatapub/postaja_json_r?p_pos_id=4',  function(err, data) {

    if (err != null) {
        console.error(err);
    } else {

        var text = data[1].Ime;

        document.getElementById("id01").innerHTML = text;


        console.log(text);
    }
    });

没有CORS插件的错误是: 从源'null'对'http://faust.izor.hr/autodatapub/postaja_json_r?p_pos_id=4'处XMLHttpRequest的访问已被CORS策略阻止:所请求的资源上没有'Access-Control-Allow-Origin'标头。

1 个答案:

答案 0 :(得分:0)

我认为该插件不是我无需任何插件即可访问api的问题。

但是,请检查以下问题:

XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin