如何制作一个PHP代理来解决CORS错误? [英] How to make a PHP proxy to solve CORS error?

查看:163
本文介绍了如何制作一个PHP代理来解决CORS错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AJAX和RESTful Web Services进行练习,但在控制台上看到一条错误消息:

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...

因此,我的代码仅能在Safari之外的任何浏览器上运行! 在所有其他浏览器(例如Chrome,Firefor或Opera)上,我都遇到了相同的错误.

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.

www.corsproxy.com解决方案非常棒,但是我只想拥有自己的代理! :-)

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

我简单的jQuery代码是:

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

哪个php代码会符合此要求?

Which will the php code be according to 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
})

位于 http://myproxy.com 的PHP部分:

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

PHP部分进行了非常简化,以使您有一个想法.

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

这篇关于如何制作一个PHP代理来解决CORS错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆