如何利用PHP 快速解决跨域问题

目录

跨域介绍

浏览器拥有同源策略限制确保安全,同源策略会阻止一个域的Javascript脚本和另外一个域的内容进行交互。

当一个请求url的协议、域名(包括多级域名)、端口三者之间任意一个与当前页面url不同即为跨域。

跨域介绍

  • 1)无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB
  • 2)无法接触非同源网页的 DOM 节点
  • 3)无法向非同源地址发送 AJAX 请求

跨域解决方案

1)JSONP(只支持GET请求)

Javascript:

<script src=\"http://test.com/data.php?callback=dosomething\"></script>
// 向服务器test.com发出请求,该请求的查询字符串有一个callback参数,用来指定回调函数的名字
 
// 处理服务器返回回调函数的数据
<script type=\"text/javascript\">
    function dosomething(res){
        // 处理获得的数据
        console.log(res.data)
    }
</script>

data.php:

header(\'Content-type: application/json\');
 
//获取回调函数名
$jsoncallback = htmlspecialchars($_REQUEST [\'callback\']);
 
//json数据
$json_data = \'[\"customername1\",\"customername2\"]\';
 
//输出jsonp格式的数据
echo $jsoncallback . \"(\" . $json_data . \")\";

2)CORS 跨域资源分享(Cross-Origin Resource Sharing)

  • 1、普通跨域请求:只需服务器端设置 Access-Control-Allow-Origin
  • 2、带cookie跨域请求:前后端都需要进行设置

PHP:

header(\"Access-Control-Allow-Origin:*\");

或者 Nginx:

location ~ .*\\.php$
{
    add_header \'Access-Control-Allow-Origin\' \'*\';    # 就加这句就行
    include fcgi.conf;
    fastcgi_pass  127.0.0.1:10080;
    fastcgi_index index.php;
    expires off;
}

Javascript:

$.ajax({
   url: \'http://www.test.com:8080/login\',
   type: \'get\',
   data: {},
   xhrFields: {
       withCredentials: true    // 前端设置是否带cookie
   },
   crossDomain: true,           // 会让请求头中包含跨域的额外信息,但不会含cookie
});
 

3)WebSocket 浏览器与服务器的全双工通信,同时也是跨域的一种解决方案

4)Nginx 反向代理

server {
    # nginx监听所有 test.com:9000 端口收到的请求
 
	listen       9000;
	server_name  test.com;
 
    # test.com:9000 会被转发到 192.168.25.20:9000
	location / {
		proxy_pass http://192.168.25.20:9000;
	}
 
	# test.com:9000/api/ 会被转发到 \"192.168.25.20:9000/api/\"
 
	location /api/ {
		proxy_pass http://192.168.25.20:9000;
	}
}
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容