关于CORS(跨源资源共享)实践

打开页面 http://www.yangyueyuan.com/home/account/login
在控制台发送跨域ajax请求:
$.ajax({
type:"get",
url:"http://tdcCenterManage.dev/index.php?abc=1",/*url写异域的请求地址*/
dataType:"json",/*加上datatype*/
success:function(){
  
}
});

http://tdcCenterManage.dev/index.php:

<?php
 echo 'success';
?>
这个请求的响应header如下:

HTTP/1.1 200 OK
Date: Mon, 03 Jul 2017 03:57:09 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By: PHP/5.6.25
Content-Length: 7
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
这个请求能正常发送,但是根据响应header浏览器报错:

login:1 XMLHttpRequest cannot load http://tdccentermanage.dev/index.php?abc=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.yangyueyuan.com' is therefore not allowed access.

http://tdcCenterManage.dev/index.php中加入header头:

header("Access-Control-Allow-Origin:*");
// 星号表示所有的域都可以接受,
header("Access-Control-Allow-Methods:GET,POST");
echo 'success';

再发送相同的ajax请求,就不报错了,响应头如下:

HTTP/1.1 200 OK
Date: Mon, 03 Jul 2017 03:56:46 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By: PHP/5.6.25
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST
Content-Length: 7
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

可以看到响应头多了两行。

CORS 背后的基本思想,就是使用自定义的HTTP 头部
让浏览器与服务器进行沟通,从而决定请求或响应是应该成功,还是应该失败。




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值