一、首先我们不能通过设置Access-Control-Allow-Origin来解决是所有的跨域问题。来看如下例子;
server.js:
const http = require('http')
const fs = require('fs')
http.createServer(function(request, response) {
console.log('request come', request.url)
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')
server2.js:
const http = require('http')
http.createServer(function(request, response) {
console.log('request come', request.url)
response.writeHead(200, {
'Access-Control-Allow-Origin': '*'
})
response.end('123')
}).listen(8887)
console.log('server listening on 8887')
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script >
fetch('http://localhost:8887', {
method: 'POST',
headers: {
'x-Test-Cors': '123'
}
})
</script>
</html>
然后启动服务,然后浏览器访问,会发现报了如下错误:
二、CORS预请求
1、CORS的其他限制
- 默认允许的方法只有:GET、HEAD、POST
- 默认允许的Content-Type:text/plain、multipart/form-data、applicaton/x-www-form-urlencoded
- 默认允许请求头:https://fetch.spec.whatwg.org里面有介绍允许的头部
- XMLHttpRequestUpload对象均没有注册任何事件监听器
- 请求中没有使用ReadableStream对象
2、什么是预请求?
我们首先将server2.修改如下:
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'
})
response.end('123')
}).listen(8887)
console.log('server listening on 8887')
这时再去访问我们会发现没有错误,然后查看network会发现比之前多了一个请求,它的Request Method是OPTIONS。通过OPTIONS请求获得服务端的允许,然后再实际的发送post请求。
3、我们该如何允许除了GET、HEAD、POST以外的其他方法呢?我们可以做如设置:
'Access-Control-Allow-Methods':'PUT'
这时我们就可以使用PUT方式进行访问。
4、Access-Control-MAX-AGE的设置,它的值是一个数字,表示多少秒,它表示的是再这个请求下面,我们以这种方式进行跨域请求持续的时间。我们第一请求以后,1000秒之内呢,跨域不再进行预请求。
'Access-Control-MAX-AGE':'1000'
设置了它以后,我们对刚刚的进行刷新,第一次有预请求,第二次没有预请求。