简单封装一下fetch
fetch发起请求的方式
fetch("./01-data.json")
.then(res => res.json())
.then(res => {
console.log(res)
})
是否是普通对象 方法
const isPlainObject = (obj) => {
let proto, Ctor;
if (!obj ||
Object.prototype.toString.call(obj) !== "[object Object]")
return false;
proto = Object.getPrototypeOf(obj);
if (!proto) return true;
Ctor = proto.hasOwnProperty("constructor") && proto.constructor;
return typeof Ctor === "function" && Ctor === Object;
}
初始化请求配置参数
let baseURL = "";
let initialConfig = {
method: "GET",
params: null,
body: null,
headers: {
"content-type": "application/json"
},
catch: "no-cache",
credentials: "include",
responseType: "json",
};
根据环境变量设置baseurl
let env = process?.env?.NODE_ENV || "development";
switch (env) {
case "development":
baseURL = "http://localhost:5500";
break;
case "production":
baseURL = "http://localhost:5500"
break;
default:
baseURL = "http://localhost:5500";
break;
}
封装fetch
const request = function request(url, config) {
if (typeof url !== "string")
throw new TypeError("url must be required and of string type!");
if (!isPlainObject(config)) config = {};
config = Object.assign({}, initialConfig, config);
if (/^http(s?):\/\//i.test(url)) url = baseURL + url;
let { method, params, body, headers, cache, credentials, responseType } = config;
if (params != null) {
if (isPlainObject(params)) {
let p = "";
for (const key in params) {
p += (key + "=" + params[key] + "&");
}
params = p.slice(0, -1);
}
url += `${url.includes("?") ? "&" : "?"}${params}`;
}
if (isPlainObject(body)) {
body = JSON.stringify(body);
} else if (typeof body === "string") {
try {
JSON.parse(body);
} catch (error) {
headers["content-type"] = "application/x-www-form-urlencoded";
}
}
let token = "token";
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
config = {
method: method.toUpperCase(),
headers,
credentials,
cache,
}
if (/^POST|PUT|PATCH$/.test(method) && body != null) config.body = body;
return fetch(url, config).then(response => {
let { status, statusText } = response;
if (status >= 200 && status < 400) {
let result;
switch (responseType.toUpperCase()) {
case "JSON":
result = response.json();
break;
case "TEXT":
result = response.text();
break;
case "BLOB":
result = response.blob();
break;
case "ARRAYBUFFER":
result = response.arrayBuffer();
break;
default:
result = response.json();
break;
}
return result;
}
return Promise.reject({
code: "STATUS ERROR",
status,
statusText
});
}).catch(reason => {
if (reason && reason.code === "STATUS ERROR") {
switch (reason.status) {
case 400:
break;
case 401:
break;
case 402:
break;
case 403:
break;
case 500:
break;
default:
break;
}
}
else if (!navigator.onLine) { }
else { }
return Promise.reject(reason);
});
};
使用封装的request方法
request("/01-data.json", {
responseType: "text"
, params: {
name: "zs"
}
})
.then(res => {
console.log(res)
}).catch(reason => {
console.log(reason)
})
|