初探 XHR 中的 Fetch 请求
fetch
与 XMLHttpRequest(XHR)类似,fetch() 方法允许你发出 AJAX 请求。区别在于 Fetch API 使用 Promise,因此是一种简洁明了的 API,比 XMLHttpRequest 更加简单易用。
比较 XMLHttpRequest(传统 Ajax)
创建步骤:
- 创建
XMLHttpRequest
对象,也就是创建一个异步调用对象 - 创建一个新的
HTTP
请求,并指定该HTTP
请求的方法、URL
及验证信息 - 发送
HTTP
请求 - 处理响应,获取异步调用返回的数据
可以发现,主要的不同点在于:传统 Ajax 使用事件处理器,而不是 Promise 对象,并且请求的发起完全依赖于xhr对象所提供的方法。
fetch 语法
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(e) {
console.log("Oops, error");
});
使用 ES6 的 箭头函数:
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
使用 async/await
来做最终优化:
(async function () {
try {
let response = await fetch(url);
let data = response.json();
console.log(data);
} catch(e) {
console.log("Oops, error", e);
}
})();
使用 await 后,写异步代码就像写同步代码一样爽。await 后面可以跟 Promise 对象,表示等待 Promise resolve() 才会继续向下执行,如果 Promise 被 reject() 或抛出异常则会被外面的 try…catch 捕获。
GET 请求
fetch(url, {
method: "GET", //默认
headers:{
"Accept": "application/json, text/plain, */*"
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
POST 请求
fetch(url, {
method: "POST",
headers: {
"Accept": "application/json, text/plain, */*",
"Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
},
body: "name=hzzly&age=22"
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
使用 Fetch 请求发送凭证
要使用 Fetch 发送带有诸如 cookie 之类的凭证的请求。你可以在选项对象中将 credentials 属性值设置为 include:
fetch(url,{
credentials: "include"
})
封装 POST 请求
//将对象拼接成 name=hzzly&age=22 的字符串形式
function params(obj) {
let result = ''
for(let item in obj) {
result += `&${item}=${obj[item]}`
}
if(result) {
result = result.slice(1)
}
return result
}
function post(url, paramsObj) {
let result = fetch(url, {
methods: 'POST',
credentials: "include"
headers: {
"Accept": "application/json, text/plain, */*",
"Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
},
body: params(paramsObj)
})
return result
}
let obj = {
name: 'hzzly',
age: 22
}
post(url, obj)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论