Skip to content

Instantly share code, notes, and snippets.

@cute-angelia
Created June 22, 2022 01:52
Show Gist options
  • Save cute-angelia/474f90aefbf71c29cf3d80f0a346efe5 to your computer and use it in GitHub Desktop.
Save cute-angelia/474f90aefbf71c29cf3d80f0a346efe5 to your computer and use it in GitHub Desktop.
post&get
get(url, headers) {
return new Promise(function (resolve, reject) {
fetch(url, {
headers: headers,
})
.then(response => response.json())
.then(data => resolve(data)).catch((error) => {
reject(error)
});
});
}
post(url = '', data = {}, headers) {
return new Promise(function (resolve, reject) {
// 处理 body
var body = "";
if (headers['Content-Type'] === 'application/x-www-form-urlencoded') {
// 把一个参数对象格式化为一个字符串
// return qs.stringify(data)
let ret = ''
for (const it in data) {
ret +=
encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
body = ret.substring(0, ret.length - 1)
} else if (headers['Content-Type'] === 'multipart/form-data;charset=UTF-8') {
// const form = new FormData();
// form.append('my_field', 'my value');
// form.append('my_buffer', new Buffer(10));
// form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
body = data
} else {
headers['Content-Type'] = 'application/json'
body = JSON.stringify(data)
}
fetch(url, {
method: 'POST',
credentials: "same-origin",
headers: headers,
// headers: {
// 'Content-Type': 'application/json',
// 'Cookie': cookies
// // 'Content-Type': 'application/x-www-form-urlencoded',
// }
body: data,
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
}).then(data => {
resolve(data);
})
.catch((error) => {
reject(error)
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment