跨域实验范例-1 (从域名domain1.com跨域到域名domain2.com上的请求访问)
192.168.10.20 domain1.com
192.168.10.20 domain2.com
[[email protected] ~]# cat >> /etc/httpd/conf.d/httpd-vhosts.conf
<Directory "/home/myth/www/site1">
Options +Indexes +FollowSymLinks
Order allow,deny
Allow from all
AllowOverride All
Require all granted
</Directory>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/home/myth/www/site1"
ServerName domain1.com
ServerAlias domain1.com
ErrorLog "/home/myth/log/httpd/domain1-com-error_log"
CustomLog "/home/myth/log/httpd/domain1-com-access_log" common
</VirtualHost>
<Directory "/home/myth/www/site2">
Options +Indexes +FollowSymLinks
Order allow,deny
Allow from all
AllowOverride All
Require all granted
</Directory>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/home/myth/www/site2"
ServerName domain2.com
ServerAlias domain2.com
ErrorLog "/home/myth/log/httpd/domain2-com-error_log"
CustomLog "/home/myth/log/httpd/domain2-com-access_log" common
</VirtualHost>
[[email protected] ~]# systemctl restart httpd && httpd -S
/home/myth/www/site1/index.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="js/jquery-3.2.1.min.js" type="text/javascript"></script>
</head>
<body>
<div class="user"></div>
</body>
<script type="text/javascript">
var url = "http://domain2.com/index.php";
$.get(url, null, function (data) {
$(".user").text("name:" + data.name + " gender:" + data.gender);
}, "json");
</script>
</html>
/home/myth/www/site2/index.php
<?php
//CORS Demo 1 : 跨域实验
$data = array(
'name' => 'Jack',
'gender' => 'Male'
);
//以下被注释掉的代码块是跨域请求的正确实现代码,首先请关注跨域请求时抛出的错误信息:
//已拦截跨源请求:同源策略禁止读取位于 http://domain2.com/index.php 的远程资源。
//(原因:CORS 头缺少 'Access-Control-Allow-Origin')
/*
//HTTP_ORIGIN是请求头中的信息,在浏览器中直接展示为Origin
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
//此处是允许跨域的白名单
$allow_origin = array(
'http://domain1.com',
'http://domain2.com'
);
//判断当前Origin来源是否在白名单内,是的话就允许设置一套三式Header头让他跨域
if (in_array($origin, $allow_origin)) {
//关键点跨域三式
header('Access-Control-Allow-Origin:' . $origin); //允许的域名
header('Access-Control-Allow-Methods:GET'); //允许的方法
header('Access-Control-Allow-Headers:X-Requested-With, Content-Type, Accept'); //服务器支持的头信息
}*/
echo json_encode($data);
?>
开始直接访问提供数据的网站site2
在FireFox浏览器地址栏里输入GET请求地址:http://domain2.com/index.php
从网站site1上去访问另外一个网站site2上提供的数据,就会立刻出现跨域请求访问的错误:
为了能从网站site1上正确实现能够跨域访问网站site2上的数据,
我们必须取消跨域请求代码块的注释/home/myth/www/site2/index.php代码如下:
<?php//CORS Demo 1 : 跨域实验
$data = array(
'name' => 'Jack',
'gender' => 'Male'
);
//以下被注释掉的代码块是跨域请求的正确实现代码,首先请关注跨域请求时抛出的错误信息:
//已拦截跨源请求:同源策略禁止读取位于 http://domain2.com/index.php 的远程资源。
//(原因:CORS 头缺少 'Access-Control-Allow-Origin')
//HTTP_ORIGIN是请求头中的信息,在浏览器中直接展示为Origin
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
//此处是允许跨域的白名单
$allow_origin = array(
'http://domain1.com',
'http://domain2.com'
);
//判断当前Origin来源是否在白名单内,是的话就允许设置一套三式Header头让他跨域
if (in_array($origin, $allow_origin)) {
//关键点跨域三式
header('Access-Control-Allow-Origin:' . $origin); //允许的域名
header('Access-Control-Allow-Methods:GET'); //允许的方法
header('Access-Control-Allow-Headers:X-Requested-With, Content-Type, Accept'); //服务器支持的头信息
}
echo json_encode($data);
?>
在FireFox浏览器地址栏里输入GET请求地址:http://domain1.com/index.html,此页面里的jquery $.get方法请求就属于从域名domain1.com跨域到域名domain2.com上的请求访问
/home/myth/www/site1/index.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="js/jquery-3.2.1.min.js" type="text/javascript"></script>
</head>
<body>
<p id="user"></p>
<button type="button" id="cors">send cors</button>
</body>
<script type="text/javascript">
$(document).ready(function () {
$("#cors").click(function (e) {
$.ajax({
url: "http://domain2.com/index.php",
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: {"id": "999", "status": true}, //发送参数
async: true,
crossDomain: true,
xhrFields: {withCredentials: true},
//beforeSend: function (xhr) {
// document.cookie = 'token=iv9ilrgr9g3tn4sgb7l0343dn7;domain=domain2.com;path=/';
//},
success: function (data) {
$("#user").text(" id = " + data.id + ", name = " + data.name + ", gender = " + data.gender + ", cookie = " + data.cookie + ", status = " + data.status);
}
});
})
});
</script>
</html>
/home/myth/www/site2/index.php
<?php
if (!isset($_COOKIE['token'])) {
setcookie('token', session_create_id(), time() + 30);
}
//CORS Demo 1 : 跨域实验
$data = array(
'id' => $_POST['id'],
'name' => 'Jack',
'gender' => 'Male',
'cookie' => $_COOKIE['token'],
'status' => $_POST['status']
);
//以下被注释掉的代码块是跨域请求的正确实现代码,首先请关注跨域请求时抛出的错误信息:
//已拦截跨源请求:同源策略禁止读取位于 http://domain2.com/index.php 的远程资源。
//(原因:CORS 头缺少 'Access-Control-Allow-Origin')
//HTTP_ORIGIN是请求头中的信息,在浏览器中直接展示为Origin
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
//此处是允许跨域的白名单
$allow_origin = array(
'http://domain1.com',
'http://domain2.com'
);
//判断当前Origin来源是否在白名单内,是的话就允许设置一套三式Header头让他跨域
if (in_array($origin, $allow_origin)) {
//关键点跨域三式
header('Access-Control-Allow-Origin:' . $origin); //允许的域名
header('Access-Control-Allow-Methods:POST,OPTIONS'); //允许的方法
header('Access-Control-Allow-Headers:X-Requested-With, Content-Type, Accept'); //服务器支持的头信息
header('Access-Control-Allow-Credentials:true');
header('Access-Controll-Max-Age:1728000');
header('Content-type: application/json');
}
echo json_encode($data);
?>