CORS跨域限制以及預請求驗證
阿新 • • 發佈:2018-12-03
之前我們可以通過“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/')
這樣設定,這個請求就成功了,但是可以觀測到多了一個請求,這個多出來的請求就是預請求,告訴瀏覽器,這個自定義請求是允許的,然後再正式的傳送這個請求,通過驗證之後就請求成功了,瀏覽器為什麼要做這些限制,是因為保證安全,不允許隨便一個人都可以進行跨域