import { fetch } from ‘dva’;
/**
- 拦截响应内容,校验状态码
- @param {request} request fetch从服务器获取到的响应内容
- @returns {promise}
*/
const checkStatus = request => {
console.log(request, ‘1’);
const { status } = request;
// 返回成功响应
if (status >= 200 && status < 300) {
return request;
}
// 响应失败
const error = new Error(request.statusText);
error.response = request;
// 抛出错误信息
throw error;
};
/**
- 拦截响应内容,取出包含返回数据
- @param {request} request fetch从服务器获取到响应内容
- @returns {promise}
*/
const parseJson = request => {
console.log(request, ‘2’);
return request.json();
};
/**
- 处理接口返回的状态包裹,直接返回数据
- @param {object} json
- @returns {object}
*/
const detection = json => {
console.log(json, ‘3’);
return json;
};
/**
- 调用 fetch 方法
- @param {string} url 请求路径
- @param {object} options 需要传递的参数, 默认为空对象
- @returns {promise}
*/
const servers = (url, options = {}) => {
return (
fetch(url, options)
// 返回经过校验码的响应内容
.then(checkStatus)
// 返回服务器给我们的结果
.then(parseJson)
// 对服务器返回的内容进行处理
.then(detection)
.catch(error => error)
);
};
/**
- get方式的参数拼接
- @param {*} url
- @param {*} options
*/
const formatUrl = (url, options = {}) => {
// 如果没有传入参数,直接返回url
if (JSON.stringify(options) === ‘{}’) {
return url;
}
// 判断url中是否存在?号
const isSearchUrl = url.includes(’?’);
const params = [];
// 取出对象中所有的key
const keys = Object.keys(options);
// 遍历key取值并将其放入一个数组
for (let key of keys) {
// 放入数组的内容是类似’key=value’的格式
params.push(key + ‘=’ + options[key]);
}
// 将数组转换成’key=value&key=value’的格式
return url + (isSearchUrl ? ‘&’ : ‘?’) + params.join(’&’);
};
/**
- 向外暴露get方法
- @param {*} url 请求路径
- @param {*} options 需要传递的参数, 默认为空对象
- @returns {promise}
*/
const get = (url, options = {}) => {
// 将待传递参数拼接到url中
const paramUrl = formatUrl(url, options);
return servers(paramUrl, {});
};
/**
- 向外暴露post方法
- @param {*} url 请求路径
- @param {*} options 需要传递的参数, 默认为空对象
- @returns {promise}
*/
const post = (url, options = {}) => {
const params = {
// 告诉fetch这是个post方法
method: ‘POST’,
// 将参数转换成fetch能接受的格式,写在body里的
// 为了避免一些关键符号被转义,所以这里我们需要encode
body:q=${encodeURIComponent(JSON.stringify(options))},
// headers,必须要用,否则接口无法获取到传入的参数
headers: {
// constentType 内容的类型
// application/x-www-form-urlencoded
‘Content-Type’: ‘application/x-www-form-urlencoded’,
},
};
return servers(url, params);
};
export default servers;
export { get, post };
本文介绍了一个自定义的fetch封装,包括检查响应状态码、解析JSON、处理返回数据等功能,并提供了GET和POST请求的实现。通过这个封装,可以更方便地进行API调用。
733

被折叠的 条评论
为什么被折叠?



