1

Is there a way to access the API from the url without the need of the Chrome extension CORS (Allow-Control-Allow-Origin)? The code works only with the extension turned on. I have no access to the remote server.

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);
    }
    });

The error without the CORS plugin is: Access to XMLHttpRequest at 'http://faust.izor.hr/autodatapub/postaja_json_r?p_pos_id=4' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

eian00
  • 21
  • 1
  • 6
  • Change your code to have `getJSON('https://cors-anywhere.herokuapp.com/http://faust.izor.hr/autodatapub/postaja_json_r?p_pos_id=4'…` and for an explanation, see the *How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems* section of the answer at https://stackoverflow.com/a/43881141/441757 – sideshowbarker May 24 '19 at 12:44
  • Thank you!, the proxy solved the problem! I was thinking there was another way around using vanilla javascript – eian00 May 24 '19 at 16:11

1 Answers1

0

I don't think the plugin is the issue I was able to access the api without any plugin.

However, do check out this question:

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

shix
  • 57
  • 11