了解fetch
fetch(input, init)
第一个参数input可以是一个字符串,包含获取资源的URL;
第二个参数对象是可选的,它可以自定义HTTP请求中的一些部分;
method: 请求使用的方法,如 GET、POST。
headers: 请求的头信息,形式为 Headers 对象或 ByteString。
body: 请求的 body 信息:可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
mode: 请求的模式,如 cors、no-cors 或者same-origin。
credentials: 请求的 credentials,如 omit、same-origin 或者include。
cache: 请求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached.
fectch()的返回值是一个Promise对象,它可以使用then和catch指定回调函数:
1
2
3
4
fetch(input, init)
.then((response) => response.json())
.then((responseJson) => {console.log(responseText);})
.catch((error) => {console.warn(error);});