fetch简介
fetch 是一个内置于现代浏览器的函数,用于在网络上进行异步请求。它返回一个 Promise,这个 Promise 在收到响应后解决,并带有一个 Response 对象作为其解决值
使用 fetch 实现异步请求
语法
fetch(url,options).then((response)=>{
//处理http响应
},(error)=>{
//处理错误
})
它是专门为了取代传统的 xhr 而生的
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
使用xhr时
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function() {
console.log(xhr.response);
};
xhr.onerror = function() {
console.log("Oops, error");
};
xhr.send();
改用fetch
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
})
fetch中的get与 post
get请求
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html', {
method: 'GET'
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
GET请求的参数传递
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html?a=1&b=2', { // 在URL中写上传递的参数
method: 'GET'
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
POST请求
与GET请求类似,POST请求的指定也是在fetch的第二个参数中:
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html', {method: 'POST' // 指定是POST请求
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)})
POST请求参数的传递
众所周知,POST请求的参数,一定不能放在URL中,这样做的目的是防止信息泄露。
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html', {method: 'POST',
body: new URLSearchParams([["foo", 1],["bar", 2]]).toString() // 这里是请求对象
})
.then((res)=>{
return res.text()
}).then((res)=>{
console.log(res)
})
fetch 的常见应用场景
fetch 可以在各种应用场景中使用,特别是在进行网络请求的情况下。以下是一些 fetch 的常见应用场景:
- 数据获取:fetch 可以用来获取远程服务器上的数据,例如从 API 获取 JSON 数据、XML 数据或 HTML 内容等。这使得我们可以在前端应用中使用这些数据来更新用户界面或执行其他操作。
- 文件下载:fetch 可以用于下载文件,例如下载图片、PDF 文件或其他类型的文件。通过将服务器响应转换为
Blob,我们可以使用 fetch 下载二进制文件。 - 表单提交:fetch 可以用来提交表单数据到服务器,例如用户注册、登录或者更新数据时。通过将请求方法设置为 POST,并将表单数据作为请求体传递给服务器。
- 身份验证:fetch 可以用于身份验证,例如在用户登录时验证凭据或者获取访问令牌。我们可以将用户提供的凭据发送到服务器进行验证,并获取相应的令牌来进行后续的操作。
- 第三方 API 调用:fetch 可以用来调用第三方提供的 API,并处理响应数据。例如,在开发中集成地图、支付、天气等服务时,我们可以使用 fetch 调用相关的 API 来获取数据。
- 实时数据更新:fetch 可以用于实时或定时更新数据,例如聊天应用中的消息获取、社交媒体更新或实时股票价格。
这只是一些 fetch 的应用场景示例,实际上,fetch 是一个非常灵活和功能强大的工具,可以在各种需要进行网络请求的情