前端開發都知道,很少說。javascript
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState !== 4) return; if (xhr.status >= 200 && xhr.status < 300) { console.log(JSON.parse(xhr.responseText)); } else { // What to do when the request has failed console.log('error', xhr); } }; xhr.open('GET', 'https://mysite.com/index'); xhr.setRequestHeader('X-Token', '123456'); xhr.send();
定義:open( Method, URL, Asynchronous, UserName, Password )
- Method:GET/POST/HEAD/PUT/DELETE/OPTIONS
- Asynchronous(defualt true)html
定義:setRequestHeader( Name, Value )
注意,以X開頭的爲header爲自定義頭部前端
定義:send(body)java
新一代旨在替換XHR的API方法。json
fetch("https://mysite.com/index", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", 'X-Token': '123456' }, body: "id=123" }).then(function (response) { if (response.ok) { return response.json(); } else { return Promise.reject({ status: response.status, statusText: response.statusText }); } }) .then(function (data) { console.log('success', data); }) .catch(function (error) { console.log('error', error); });
定義:fetch(input, init)api
fetch返回一個promise,採用then的鏈式調用避免回調地獄問題。跨域
參考這裏:https://developer.mozilla.org/zh-CN/docs/Web/API/Responsepromise
CORS是一種機制,用來保護跨域數據傳輸的安全性和下降風險。瀏覽器
Access-Control-Request-Method
(Preflight使用)客戶端告訴服務器實際請求時使用的方法。緩存
Origin
客戶端請求從哪一個域來
1. OPTIONS /resources/post-here/ 2. HTTP/1.1 3. Host: bar.other 4. User-Agent: Mozilla/5.0 (Macintosh; U; 5.Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre 6. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 7. Accept-Language: en-us,en;q=0.5 8. Accept-Encoding: gzip,deflate 9. Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 10. Connection: keep-alive 11. Origin: http://foo.example 12. Access-Control-Request-Method: POST 13. Access-Control-Request-Headers: X-PINGOTHER, Content-Type //響應 14. HTTP/1.1 200 OK 15. Date: Mon, 01 Dec 2008 01:15:39 GMT 16. Server: Apache/2.0.61 (Unix) 17. Access-Control-Allow-Origin: http://foo.example 18. Access-Control-Allow-Methods: POST, GET, OPTIONS 19. Access-Control-Allow-Headers: X-PINGOTHER, Content-Type 20. Access-Control-Max-Age: 86400 21. Vary: Accept-Encoding, Origin 22. Content-Encoding: gzip 23. Content-Length: 0 24. Keep-Alive: timeout=2, max=100 25. Connection: Keep-Alive 26. Content-Type: text/plain
跨域請求分爲簡單請求和預檢請求,所有符合下列條件時爲簡單請求:
當使用普通請求時,若是服務器容許該源域跨域請求資源,則直接返回響應。若是服務器不容許跨域請求,則返回不正確的響應首部,則請求方不會收到任何數據。
除了簡單請求的狀況,其餘的CORS請求都會有預檢請求。
預檢請求會先使用OPTIONS方法發起一個預檢請求到服務器,以獲知服務器是否容許該實際請求,因此會進行2個回合的通訊。
典型的會觸發預檢請求的跨域情景:請求JSON數據 或 帶有自定義頭部
如:
跨域請求的一種常見實現方式.
<script type="text/javascript"> function jsonpCallBack(data){ console.log(data.msg); } $(document).ready(function(){ $("body").append('<script src="http://www.ASite.com/ServerJSONP.js?callback=jsonpCallBack"></script>'); }); </script>
jsonpCallBack({msg:"this is jsonp request!"});
refs:
https://xhr.spec.whatwg.org/
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
https://gomakethings.com/why-i-still-use-xhr-instead-of-the-fetch-api/
https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS