前端开发都知道,不多说。
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)
定义:setRequestHeader( Name, Value )
注意,以X开头的为header为自定义头部
定义:send(body)
新一代旨在替换XHR的API方法。
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)
fetch返回一个promise,采用then的链式调用避免回调地狱问题。
参考这里:https://developer.mozilla.org/zh-CN/docs/Web/API/Response
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数据 或 带有自定义头部
如:
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
原文:https://www.cnblogs.com/full-stack-engineer/p/9818697.html