Enable 'Access-Control-Allow-Origin' in jQuery [xml]

Asked

Viewed 2,363 times

1

I don’t have access to .htaccess server and need to enable Cors on jQuery

The code to access Webservice is:

$(document).ready(function(){
    jQuery.support.cors = true;
    $.ajax({
        url: 'https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote',
        crossDomain:true,
        dataType: 'text/xml',
        success: function(response){
            console.log(response);
        }
    });
});

The request headers is:

Request Headers
:authority:finance.yahoo.com
:method:GET
:path:/webservice/v1/symbols/allcurrencies/quote
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
origin:http://localhost
referer:http://localhost/biblioteca/cotacao/jQueryYahooFinance/
user-agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/59.0.3071.109 Chrome/59.0.3071.109 Safari/537.36

No . htaccess I would activate using:

Header set Access-Control-Allow-Origin "*"

In php I would activate using:

<?php header('Access-Control-Allow-Origin: *'); ?>

3 answers

1


The Access-Control-Allow-Origin can only be activated on the server. The purpose of this rule is that the browser cannot access content that the server does not want accessed when the request domain is not the same as the server domain.

  • I thought I could, because I can through PHP.

1

should be added to the .xml (which is not possible because it is the Yahoo server, only they have this control) and nay on your page, if it were possible to do this directly by the customer would be a security breach and would not need control of Cors.

However it is possible to create a "web-proxy" with curl to get around this, an example:

Create a file called moedas.php and add this:

<?php

$url = 'https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

//Define um User-agent
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

//Retorna a resposta
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Resposta
$data = curl_exec($ch);

if($data === false) {
    echo 'Erro ao executar o CURL: ' . curl_error($ch);
} else {
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpcode !== 200) {
        header('X-PHP-Response-Code: ' . $httpcode, true, $httpcode);
        die('Erro ao requisitar o servidor');
    }
}

header('Content-Type: text/xml');

//Exibe dados
echo $data;

So in Ajax call:

$(document).ready(function(){
    $.ajax({
        url: 'moedas.php',
        success: function(response){
            console.log(response);
        },
        error: function(err){
            console.log(err);
        }
    });
});

Note: if you are using PHP 5.4+ you can swap header('X-PHP-Response-Code: ' . $httpcode, true, $httpcode); for http_response_code($httpcode);

  • 1

    Thanks for the help. This is an interesting way.

0

If create a php file and do:

<?php
    call_user_func($_POST['funcao']);
    function cotacao(){
        /* Faço load do arquivo xml */
        $xml = simplexml_load_file('https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote');
        /* Retono uma String xml bem formada */
    echo $xml->asXML();
    }
?>

And call this document:

$(document).ready(function(){
    $.ajax({
        url: 'documento.php',
        dataType: 'text/xml',
        type: 'post',
        success: function(response){
            console.log(response);
        }
    });
});

It works that is a wonder, I wanted to make this direct call by jQuery, but from what I understood there is no way.

  • The problem with this solution is that it has SHARED and VPS servers that block in php.ini or allow_url_fopen, https://secure.php.net/manual/en/filesystem.configuration.php. On these servers it is not possible to enable, otherwise using it on HTTPS servers may not work if you do not configure "security certificates" in php.ini or on stream_context_create, Curl is easier to set up, or even ignore security.

  • Thank you for the information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.