我已经构建了一个函数来调用 fetch 并设置我需要设置的所有参数。它工作完美,但我想稍微改进一下。目前我有两个版本,一个用于 GET 方法,另一个用于 POST 方法。这是因为对于 POST 我需要传递一个正文,而对于 GET 则不需要。我想让函数中的 body 参数成为可选的,并且仅在设置为 GET 请求时才包含在 fetch 中。
这是 GET 情况下的相关部分
async function getData(url = "") {
const response = await fetch(url, {
method: "GET",
mode: "cors",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
});
这是 POST 情况下的相关部分
async function postData(url = "", data = {}) {
const response = await fetch(url, {
method: "POST",
mode: "cors",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
以下是如何创建一个名为 fetchData 的统一函数,该函数处理 GET 和 POST 请求,以及可能的其他 HTTP 方法:
async function fetchData(url = "", method = "GET", data = null) {
const options = {
method: method,
mode: "cors",
credentials: "include",
headers: {
"Content-Type": "application/json",
}
};
if (method === "POST" && data !== null) {
options.body = JSON.stringify(data);
}
const response = await fetch(url, options);
return response.json();
}
我想你可以简单地编写第三个函数来执行
send
喜欢:
function send(url, options) {
if (!url) {
throw 'url not specified';
}
return fetch( url, {
mode: 'cors',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
...options });
}
function getData(url) {
return send( url, { method: 'GET' });
}
function postData(url, body) {
return post( url, { method: 'POST', body: body ? JSON.stringify( body ) : null });
}
这将允许您随后添加更多方法并将标题逻辑保留在一个位置