
fetch使用
fetch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| fetch('https://api.example.com/data') .then(response => { if (response.ok) { return response.json(); } throw new Error('Network response was not ok.'); }) .then(data => { console.log(data); }) .catch(error => { console.error('Error:', error); });
const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'aaaa', age: 30 }) }; fetch('https://api.example.com/users', requestOptions) .then(response => { if (response.ok) { return response.json(); } throw new Error('Network response was not ok.'); }) .then(data => { console.log(data); }) .catch(error => { console.error('Error:', error); });
|
fetch请求配置
请求的配置项,可选参数如下:
method
: 请求使用的方法,如GET
、POST
。headers
: 请求的头信息,形式为Headers
的对象或包含ByteString
值的对象字面量。body
: 请求的body信息,可能是一个Blob
、BufferSource
、FormData
、URLSearchParams
或者USVString
对象。mode
: 请求的模式,如cors
、no-cors
或者same-origin
。credentials
: 请求的credentials
,如 omit
、same-origin
或者include
。为了在当前域名内自动发送cookie
,必须提供这个选项。cache
: 请求的cache
模式: default
、no-store
、reload
、no-cache
、force-cache
或者only-if-cached
。redirect
: 可用的redirect
模式: follow
(自动重定向),error
(如果产生重定向将自动终止并且抛出一个错误), 或者manual
(手动处理重定向)。referrer
: 一个USVString
可以是no-referrer
、client
或一个URL
。默认是 client
fetch响应处理
如果响应成功(状态码为200-299之间),则进行响应处理
json()
方法:将响应体解析为JSON格式,并返回一个Promise对象,可以使用.then()
方法获取解析后的数据。text()
方法:将响应体解析为纯文本,并返回一个Promise对象。blob()
方法:将响应体解析为二进制数据,并返回一个Promise对象。
fetch缺点
XMLHttpRequest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function(){ console.log(httpRequest.readyState);
if(httpRequest.readyState===4){ if(httpRequest.status===200){ console.log(httpRequest.response);
var data = JSON.parse(httpRequest.response); console.log(data); } }
}
var url = "http://127.0.0.1:7777/list";
httpRequest.open('GET',url,true);
httpRequest.setRequestHeader("Content-Type","application/json");
httpRequest.send(null);
|