Access-Control-Allow-Origin error sending a jQuery Post to Google API's

前端 未结 7 1720
小蘑菇
小蘑菇 2020-11-22 14:04

I read a lot for the \'Access-Control-Allow-Origin\' error, but I don\'t understand what I have to fix :(

I\'m playing with Google Moderator API, but when I try to a

7条回答
  •  攒了一身酷
    2020-11-22 14:28

    There is a little hack with php. And it works not only with Google, but with any website you don't control and can't add Access-Control-Allow-Origin *

    We need to create PHP-file (ex. getContentFromUrl.php) on our webserver and make a little trick.

    PHP

    
    

    JS

    $.ajax({
        method: 'POST',
        url: 'getContentFromUrl.php', // link to your PHP file
        data: {
            // url where our server will send request which can't be done by AJAX
            'ext_url': 'https://stackoverflow.com/questions/6114436/access-control-allow-origin-error-sending-a-jquery-post-to-google-apis'
        },
        success: function(data) {
            // we can find any data on external url, cause we've got all page
            var $h1 = $(data).find('h1').html();
    
            $('h1').val($h1);
        },
        error:function() {
            console.log('Error');
        }
    });
    

    How it works:

    1. Your browser with the help of JS will send request to your server
    2. Your server will send request to any other server and get reply from another server (any website)
    3. Your server will send this reply to your JS

    And we can make events onClick, put this event on some button. Hope this will help!

提交回复
热议问题