🏠 Home 

Async_Requests

异步Requests库

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greasyfork.org/scripts/431423/964206/Async_Requests.js

  1. // ==UserScript==
  2. // @name Async_Requests
  3. // @namespace https://blog.chrxw.com
  4. // @version 1.1
  5. // @description 异步Requests库
  6. // @author Chr_
  7. // ==/UserScript==
  8. //==============================================================
  9. class Request {
  10. constructor(timeout = 3000) {
  11. this.timeout = timeout;
  12. }
  13. get(url, opt = {}) {
  14. return this.baseRequest(url, 'GET', opt, 'json');
  15. }
  16. getHtml(url, opt = {}) {
  17. return this.baseRequest(url, 'GET', opt, '');
  18. }
  19. getText(url, opt = {}) {
  20. return this.baseRequest(url, 'GET', opt, 'text');
  21. }
  22. post(url, data, opt = {}) {
  23. opt.data = JSON.stringify(data);
  24. return this.baseRequest(url, 'POST', opt, 'json');
  25. }
  26. baseRequest(url, method = 'GET', opt = {}, responseType = 'json') {
  27. Object.assign(opt, {
  28. url, method, responseType, timeout: this.timeout
  29. });
  30. return new Promise((resolve, reject) => {
  31. opt.ontimeout = opt.onerror = reject;
  32. opt.onload = ({ readyState, status, response, responseText }) => {
  33. if (readyState === 4 && status === 200) {
  34. if (responseType == 'json') {
  35. resolve(response);
  36. } else if (responseType == 'text') {
  37. resolve(responseText);
  38. }
  39. } else {
  40. console.error('网络错误');
  41. console.log(readyState);
  42. console.log(status);
  43. console.log(response);
  44. reject('解析出错');
  45. }
  46. }
  47. GM_xmlhttpRequest(opt);
  48. });
  49. }
  50. }
  51. const $http = new Request();