Http 跨域(Cors) 详解
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Http 跨域(Cors) 详解相关的知识,希望对你有一定的参考价值。
参考技术A 1.构成跨域的条件(满足下方任意一个条件则构成跨域)domain不同(域名或者ip不同)
端口不同
协议不同(http/https)
给大家展示一个请求头和响应头,这是满足跨域的
请求头
```
POST http://127.0.0.1:10030/user/login HTTP/1.1
Host: 127.0.0.1:10030
Connection: keep-alive
Content-Length: 33
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (Khtml, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7
Cookie: cna=CKV9Ew45tVYCAX1SFKx2d19k; _uab_collina=152896489958250435552525; _umdata=65F7F3A2F63DF020E1473F196945E27DBC990F7BBC00081CD2D29B2B4AD9F1FCC05972083687D762CD43AD3E795C914CD2FEBFBF6205958F64E60BC7B372D87F; Hm_lvt_31d8fd22bdec2e7ab9e5855741f0fac1=1541048271,1541503268,1542598403,1543222019; SESSION=NDllODZlMWQtODk5ZC00MDg3LThiN2ItNGM0MTRlMjZlOTFm
phone=15555555555&password=111111
```
响应头
```
HTTP/1.1 200
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Allow-Credentials: true
Set-Cookie: rememberMe=deleteMe; Path=/; Max-Age=0; Expires=Tue, 01-Jan-2019 06:44:30 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 02 Jan 2019 06:44:30 GMT
103
"data":"id":2,"name":null,"nickName":"15555555555","email":null
0
```
详解
首先请求头中需要设置,这个是设置跨域的的协议,domain 和端口,也就是浏览器地址的栏的根路径
```
Origin: http://localhost:8080
```
服务器获取到这个请求头之后开始进行校验校验成功后,设置响应头
Access-Control-Allow-Origin 参数建议不要设置为 * 设置为 * 的话,其他的请求时则不会带上 Cookie
```
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Allow-Credentials: true
```
将这个响应头设置好返回给浏览器,就达到跨域的效果了
其他和跨域有关的响应头
```
//预检结果缓存时间,也就是上面说到的缓存啦
'Access-Control-Max-Age: 1800'
//允许的请求类型
'Access-Control-Allow-Methods:GET,POST,PUT,POST'
//允许的请求头字段
'Access-Control-Allow-Headers:x-requested-with,content-type'
```
参考链接 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
以上是关于Http 跨域(Cors) 详解的主要内容,如果未能解决你的问题,请参考以下文章