博客
关于我
前端提高篇(115):简单了解CORS跨域资源共享
阅读量:142 次
发布时间:2019-02-26

本文共 1227 字,大约阅读时间需要 4 分钟。

1.基本概念

同源,指的是协议、域名、端口均一致
之前提到的ajax遵循同源策略,之前我们用jsonp技术,借用script的src不受跨域影响的特性来请求资源,但有一定的局限性,仅支持GET请求;还有一种打破跨域限制的方法,就是CROS,可以支持所有类型的HTTP请求

cross-origin resource sharing(CORS)跨域资源共享:是一种使用额外HTTP首部实现跨域获取资源权限的机制

XMLHttprequest获取非同源资源会被浏览器拦截,除非响应报文包含了正确CORS响应头

如果服务器没有CORS响应头的设置,就会报错:No 'Access-Control-Allow-Origin' header is present on the requested resource

在php文件上加上Access-Control-Allow-Origin响应头(访问控制允许源):

header('Access-Control-Allow-Origin:*');

报错就消失了,*代表允许所有源来访问

(后面的值可以是特定的域名,代表允许这个源来获取资源,若不设置此项默认只有同源才能获取)
在这里插入图片描述

2.分类

2.1.简单请求
2.1.1 使用下列方法之一:
GET / POST / HEAD
2.1.2content-type值为下列之一
text/plain
multipart/form-data
application / x-www-form-urlencoded等
总而言之,前端仅需正常写,服务器配置响应头即可

2.2.预检请求:预先判断检查服务器是否允许处理这个请求

先用OPTIONS方式向服务器发起预检请求,服务器允许了,才能进行之后的资源请求
预检请求有一个有效期,在该有效期内,同样的资源请求不需要再发送预检请求

满足以下条件之一就需要发送预检请求:

1.使用非HEAD / POST / HEAD方法
2.content-type值不为下列之一
text/plain
multipart/form-data
application / x-www-form-urlencoded
3.人为设置了CORS安全的首部字段集合之外的首部字段

如,在发送请求时,人为设置了一个头部:X-user

在这里插入图片描述

需要在服务器设置允许此请求头:

header('Access-Control-Allow-Origin:*'); //允许访问源为所有header("Access-Control-Allow-Method:POST,GET,OPTIONS"); //允许发送的方法header("Access-Control-Allow-Header:X-user,Content-Type"); //允许设置的请求头header("Access-Control-Allow-Max-Age:86400"); //允许预检信息缓存的有效期

在这里插入图片描述

转载地址:http://pspk.baihongyu.com/

你可能感兴趣的文章
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>