Cors cross-domain request principle

A simple and complete case of CORS ajax cross-domain request php

This article was posted on Friday, February 9th, 2018 at 00:29 and is categorized under  js instances . Read 6602 times, 7 times today

一、CORS: Cross-Origin Resource Sharing

CORS is the abbreviation of Cross-Origin Resource Sharing, which means cross-domain resource sharing, not only across subdomains, but also resource acquisition even if the domain names are completely different.

One of the more common applications is Ajax cross-domain request data.

This feature IE11 starts to support:

ajax cross-domain access browser compatibility

Like the stock market, the great rivers and mountains are green, and the green grasslands are endless.

2. Header settings and cases for ajax cross-domain requests

Compared with traditional ajax requests, the occasional workload of ajax cross-domain requests is mainly on the data receiver side, that is, set on the server side.

举个例子,假设我们服务端使用的是世界上最好的语言PHP,且ajax请求页面的名称是cors-ajax.php,那么,我们可以在此PHP页面进行如下header设置:

// 设置允许其他域名访问
header('Access-Control-Allow-Origin:*');  
// 设置允许的响应类型 
header('Access-Control-Allow-Methods:POST, GET');  
// 设置允许的响应头 
header('Access-Control-Allow-Headers:x-requested-with,content-type'); 

Access-Control-Allow-Origin:*表示任何域名请求我,我都不会将别人拒之千里之外。通常实际开发的时候,我们这里会设置信任的域名,例如:

header('Access-Control-Allow-Origin:http://www.iknowu.com');

如果是多个域名,可以使用英文逗号进行分隔,和上面Access-Control-Allow-Methods的书写格式一致。

只要在PHP页面中进行了上面设置,剩下的工作就和传统的ajax请求基本上没有任何区别。

例如什么也不干,就随机返回一个小美女的图片地址:

<?php
// 刚出现的那些header... 

echo 'http://image.zhangxinxu.com/image/study/s/s128/mm'. rand(1,20) .'.jpg'; 
?>

此时我们随随便便建一个HTML页面,写下下面这段极简的XMLHttpRequest请求JS代码:

var xhr = new XMLHttpRequest();
xhr.open('post', 'http://www.zhangxinxu.com/study/201802/cros-ajax.php');
xhr.onload = function () {
    console.log(xhr.responseText);
};
xhr.send(null);

我们就能请求到cors-ajax.php随机返回的图片地址。

眼见为实,您可以狠狠地点击这里:CORS ajax跨域请求测试demo/

可以看到,我们的demo测试页面地址是:http://zxx.xiliz.com/cors-ajax

也就是域名是zxx.xiliz.com,而请求的php页面域名是www.zhangxinxu.com,典型的跨域请求场景,下面看看会发生什么:

点击demo页面上按钮,然后当当当当:

Screenshot of successful cross-domain ajax request

成功请求到了随机图片地址,并在页面上呈现出来。

噢耶!

三、结束语

小而美实用案例一则,给自己备个忘。

我蓦然一看,时间还算早,要不再随便扯点其他,刚又买了个域名canvasapi.cn,打算搞个canvasapi中文文档,不过应该抽不出那么多时间,这个计划90%+会流产,还是等以后再说吧。

下周就要过年了提前祝大家汪年快乐,万事如意。

(本篇完)// 想要打赏?点击这里。有话要说?点击这里

分享到:

Sponsor recommendation ( I want to sponsor too ) :



Leave a comment (currently 9 comments)

 name (required)

 Email address (will not be published) (required)

 website

Copyright© 2009-2018 Zhang Xinxu-Xin Space-Xin Life
Hubei ICP No. 09015569

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324762970&siteId=291194637