How to make a PHP proxy to solve CORS error?

2019-06-07 13:28发布

I'm practicing on AJAX and RESTful Web Services and i got an error on console which says:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ... blah blah blah...

So, my code doesn't run on any browser except Safari! On every other browser like Chrome, Firefor or Opera i got the same error.

As long as i have searched through the internet, i found that the only way to achieve this is to make a proxy server which will send the request to the server and then append some headers on the response back to client.

The www.corsproxy.com solution its great, but i just want to have my own proxy! :-)

My simple jQuery code is:

            var dataURL = "http://fou.com/last.json";
            $.ajax({
                url: dataURL,
                async: true,
                type: "GET",
                dataType: "json",
                success: editData
            // editData it's a function which gonna edit the data from fou.com ..
            })

Which will the php code be according to this?

1条回答
smile是对你的礼貌
2楼-- · 2019-06-07 14:21

You can do something like this:

JS:

var dataURL = "http://fou.com/last.json";
var proxyUrl = "http://myproxy.com/?get=";
$.ajax({
    url: proxyUrl+encodeURIComponent(dataURL),
    async: true,
    type: "GET",
    dataType: "json",
    success: editData
})

PHP part at http://myproxy.com :

<?php
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $_GET['get']
    ));
    curl_exec($curl);
?>

The PHP part is very simplified to give you an idea.

查看更多
登录 后发表回答