推荐答案
// www.javascriptcn.com code example
function fetch(url, options = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(options.method || 'GET', url);
if (options.headers) {
for (let [key, value] of Object.entries(options.headers)) {
xhr.setRequestHeader(key, value);
}
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
status: xhr.status,
statusText: xhr.statusText,
headers: xhr.getAllResponseHeaders(),
body: xhr.responseText
});
} else {
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = () => {
reject({
status: xhr.status,
statusText: xhr.statusText
});
};
xhr.send(options.body || null);
});
}本题详细解读
1. 函数定义
fetch(url, options) 是一个自定义的 fetch 函数,模拟了浏览器的 Fetch API。
url 是请求的目标地址。
options 是一个可选参数,用于配置请求的方法、头部、请求体等。
2. 使用 XMLHttpRequest
- 该函数内部使用了
XMLHttpRequest 对象来发送请求。
xhr.open(options.method || 'GET', url) 初始化请求,默认使用 GET 方法。
- 如果
options.headers 存在,遍历并设置请求头。
3. 处理响应
xhr.onload 事件处理程序在请求成功时触发。
- 如果状态码在 200 到 299 之间,表示请求成功,返回一个包含状态码、状态文本、响应头和响应体的对象。
- 如果状态码不在这个范围内,表示请求失败,返回一个包含状态码和状态文本的错误对象。
4. 处理错误
xhr.onerror 事件处理程序在请求失败时触发,返回一个包含状态码和状态文本的错误对象。
5. 发送请求
xhr.send(options.body || null) 发送请求,如果 options.body 存在,则将其作为请求体发送。
6. 返回 Promise
- 该函数返回一个
Promise,在请求成功时 resolve,失败时 reject。