External URL request Ajax

0

I'm having the following problem, I implemented the code, to get RSS blog info, however I'm not getting url accessing critiquing error 401, when I place local file it works normally.

var ajax = new XMLHttpRequest();

    ajax.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log("Dados" + ajax.responseText);
            startComunicado(this);
        }
    };
    ajax.open("GET", "http://www.infomoney.com.br/blogs/investimentos/off-the-records/rss", true);
    ajax.send();
};
    
asked by anonymous 07.03.2018 / 13:24

2 answers

0

Do as follows

                  $.ajax({
                    type: 'GET',
                    crossDomain: true,
                    data: form,
                    dataType: 'json',
                    url: 'http://www.infomoney.com.br/blogs/investimentos/off-the-records/rss',


                    success: function (dados) {
                        if (dados != null) {

                           //fazer o que quiser
                        }

                    },
                    error: function () {
                        console.log("Falha de enviar AJAX");
                    }
                })

    
07.03.2018 / 13:27
0

The error Status Code 401 happens when you make a request, but you do not have permission.

Already the error quoted in the previous response comment:

"Failed to load infomoney.com.br/blogs/investimentos/off-the-records/rss: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost'; is therefore not allowed access."

It happens because the header Access-Control-Allow-Origin is missing from the server response.

To work around this, you can use the https://cors.io/ site. It will serve as an intermediary and will automatically add the required header .

Example with Fetch:

fetch("https://cors.io/?http://www.infomoney.com.br/blogs/investimentos/off-the-records/rss")
    .then( resp => resp.text() )
    .then(resp => console.log(resp))
    .catch( err => console.debug(err) );

Example with XHR:

var ajax = new XMLHttpRequest();

ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(ajax.responseText);
    }
};
ajax.open("GET", "https://cors.io/?http://www.infomoney.com.br/blogs/investimentos/off-the-records/rss", true);
ajax.send();
    
07.03.2018 / 14:16