使用Fetch API发送GET请求的基本语法如下:
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
其中,url为请求的地址。Fetch API返回一个Promise对象,可以使用.then()方法处理返回结果,也可以使用.catch()方法处理错误。
使用Fetch API发送POST请求的基本语法如下:
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
其中,url为请求的地址,data为POST请求的数据。需要注意的是,POST请求需要在请求头中设置Content-Type为application/json,并将请求数据转换为JSON字符串。
Fetch API返回的结果是一个Response对象,可以通过该对象的方法和属性获取返回的数据。
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
需要注意的是,需要先判断Response对象的ok属性是否为true,如果不为true,说明请求出错,需要抛出错误。
Fetch API使用Promise对象处理错误,可以使用.catch()方法捕获错误。
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
可以在.catch()方法中处理错误,比如输出错误信息。