基于umi的开发模板

request_helper.ts 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. function checkStatus(response: any) {
  2. if (response.status >= 200 && response.status < 300) {
  3. return response;
  4. }
  5. const error = new Error(response.statusText);
  6. throw error;
  7. }
  8. export function parseUrl(obj: any): string {
  9. let result:string = "?";
  10. for (let key in obj) {
  11. if (obj[key]) {
  12. if (result === "?") {
  13. result += `${key}=${obj[key]}`;
  14. } else {
  15. result += `&${key}=${obj[key]}`;
  16. }
  17. }
  18. }
  19. if (result === "?") return "";
  20. return result;
  21. }
  22. /**
  23. * Requests a URL, returning a promise.
  24. *
  25. * @param {string} url The URL we want to request
  26. * @param {object} [options] The options we want to pass to "fetch"
  27. * @return {object} An object containing either "data" or "err"
  28. */
  29. export default async function request(url: string, options: any = {}): Promise<any> {
  30. let data, response: any;
  31. try {
  32. response = await fetch(url, { credentials: 'include', ...options });
  33. checkStatus(response);
  34. if (!response.body) return true;
  35. data = await response.clone().json();
  36. } catch (err) {
  37. if (response && response.clone) {
  38. data = await response.clone().text();
  39. }
  40. return false;
  41. }
  42. return data;
  43. }