CORS跨域限制以及预请求验证

之前我们可以通过“Access-Control-Allow-Origin”,实现跨域请求,那是不是所有跨域请求都可以通过设置Access-Control-Allow-Origin实现跨域请求呢?显然不是,它也会有一些限制
//server.js
const http = require('http');
const fs = require('fs');

http.createServer(function(req,res){
  console.log('req come', req.url);
  const html = fs.readFileSync('test.html', 'utf8');
  res.writeHead(200,{
    'Content-Type': 'text/html'
  })
  res.end(html);
}).listen(8888);

console.log('server listening on 8888');
console.log('http://localhost:8888/')

  

//server2.js
const http = require('http');

http.createServer(function(req,res){
  console.log('req come', req.url);
  res.writeHead(200, {
    'Access-Control-Allow-Origin': '*'
  })
  res.end('345');
}).listen(8887);

console.log('server listening on 8887');
console.log('http://localhost:8887/')
<!--test.html-->
<body>
<script>
fetch('http://localhost:8887/',{
  method:'post',
  headers:{
    'X-Test-Cors':'123'
  }
})
</script>
</body>

启动服务,运行server.js,请求8887,发现报错了,而且报错信息跟之前也会有点不一样,提示‘X-Test-Cors’,这个头信息在跨域里面是不被允许的,这就是今天要讲的cors跨域限制

一、跨域请求里面允许的方法
get
head
post
其它都是不允许的,比如put,delete等,浏览器预请求里面是做了验证的,
二、允许的Content-Type
text/plain
multipart/form-data
application/x-www-form-urlencoded
其它的content-type也需要经过预请求验证过才能发送
三、其他限制
请求头限制:比如刚才的自定义请求头,其他允许的请求头(https://fetch.spec.whatwg.org/#cors-safelisted-request-header)
XMLHttpRequestUpload对象均没有注册任何事件监听器
请求中没有使用ReadableStream对象



四、什么是预请求
刚才的请求是有返回值的,但是报错了,忽略了这个值,要不忽略这个值,需要在返回值里面允许这个自定义的头信息
// server2.js
const http = require('http');
http.createServer(function(req,res){
  console.log('req come', req.url);
  res.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", //1000秒内不用再次发送预请求来验证,直接发起正式的请求就可以
  })
  res.end('345');
}).listen(8887);
console.log('server listening on 8887');
console.log('http://localhost:8887/')

这样设置,这个请求就成功了,但是可以观测到多了一个请求,这个多出来的请求就是预请求,告诉浏览器,这个自定义请求是允许的,然后再正式的发送这个请求,通过验证之后就请求成功了,浏览器为什么要做这些限制,是因为保证安全,不允许随便一个人都可以进行跨域

原文地址:https://www.cnblogs.com/wzndkj/p/10056563.html