深入HTTP-跨域请求
什么是CORS
CORS即Cross-Origin Resource Sharing–跨资源共享,当一个请求url的协议,域名,端口三者之间与当前页面地址不同即为跨域。
CORS需要浏览器和服务器同时支持,目前所有浏览器都支持该功能,IE浏览器不能低于IE10。整个CORS通信过程都是浏览器自动完成,不需要用户参与。实现CORS通信的关键是服务器,只要服务器实现了CORS接口,就可以跨域通信。
两种请求
浏览器将CORS请求分为两类:简单请求和非简单请求。
主要同时满足以下两大条件,就属于简单请求。
(1)请求方法是以下三种方法之一
- HEAD
- GET
- POST
(2)HTTP的头信息不超出以下几种字段
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-Type:限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain
凡是不同时满足上面两个条件,就属于非简单请求。
浏览器对这两种请求的处理是不同的。
简单请求
简单请求时,浏览器会直接发送跨域请求,并在请求头部中携带Origin的header,表明这是一个跨域请求。服务器端接到请求后,会根据自己的跨域规则,通过Access-Control-Allow和Access-Control-Allow-Methods响应头,来返回验证结果
创建url为localhost:8888的服务器
const http = require('http')
const fs = require('fs')
http.createServer(function (request, response) {
console.log('request come', request.url)
<!-- 请求test.html-->
const html = fs.readFileSync('test.html', 'utf8')
response.writeHead(200, {
'Content-Type': 'text/html'
})
response.end(html)
}).listen(8888)
console.log('server listening on 8888')
创建test.html,通过该html实现跨域
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
fetch('http://127.0.0.1:8887', { //请求url为localhost:8887资源
method: 'POST',
headers: {
}
})
</script>
</html>
预先请求(非简单请求)
当非简单请求时,浏览器会先发送一个OPTION请求,用来与目标域名服务器协商决定是否可以发送实际的跨域请求。
浏览器在发现页面中有上述条件的动态跨域请求的时候,并不会立即执行对应的请求代码,而是会先发送Preflighted requests(预先验证请求),Preflighted requests是一个OPTION请求,用于询问要被跨域访问的服务器,是否允许当前域名下的页面发送跨域的请求。
重写test.html文件,在请求头部中添加内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
fetch('http://127.0.0.1:8887', {
method: 'POST',
headers: {
'X-Test-Cors': '123' //自定义头部
}
})
</script>
</html>
接收跨域请求的服务器
const http = require('http')
http.createServer(function (request, response) {
console.log('request come', request.url)
response.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'X-Test-Cors', //允许此头部
'Access-Control-Allow-Methods': 'POST, PUT, DELETE',
'Access-Control-Max-Age': '1000'
})
response.end('123')
}).listen(8887)
console.log('server listening on 8887')