wzp
2021-05-13 7d694a9113118daec5be7ac224dab46a3b20f106
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import {URL} from 'url';
import {HttpVerb, Response} from 'then-request';
import handleQs from 'then-request/lib/handle-qs.js';
import {Options} from './Options';
import GenericResponse = require('http-response-object');
 
const fd = FormData as any;
export {fd as FormData};
export default function doRequest(
  method: HttpVerb,
  url: string | URL,
  options?: Options
): Response {
  var xhr = new XMLHttpRequest();
 
  // check types of arguments
 
  if (typeof method !== 'string') {
    throw new TypeError('The method must be a string.');
  }
  if (url && typeof url === 'object') {
    url = url.href;
  }
  if (typeof url !== 'string') {
    throw new TypeError('The URL/path must be a string.');
  }
  if (options === null || options === undefined) {
    options = {};
  }
  if (typeof options !== 'object') {
    throw new TypeError('Options must be an object (or null).');
  }
 
  method = method.toUpperCase() as any;
  options.headers = options.headers || {};
 
  // handle cross domain
 
  var match;
  var crossDomain = !!(
    (match = /^([\w-]+:)?\/\/([^\/]+)/.exec(url)) && match[2] != location.host
  );
  if (!crossDomain) options.headers['X-Requested-With'] = 'XMLHttpRequest';
 
  // handle query string
  if (options.qs) {
    url = handleQs(url, options.qs);
  }
 
  // handle json body
  if (options.json) {
    options.body = JSON.stringify(options.json);
    options.headers['content-type'] = 'application/json';
  }
  if (options.form) {
    options.body = options.form as any;
  }
 
  // method, url, async
  xhr.open(method, url, false);
 
  for (var name in options.headers) {
    xhr.setRequestHeader(name.toLowerCase(), '' + options.headers[name]);
  }
 
  // avoid sending empty string (#319)
  xhr.send(options.body ? options.body : null);
 
  var headers = {};
  xhr
    .getAllResponseHeaders()
    .split('\r\n')
    .forEach(function(header) {
      var h = header.split(':');
      if (h.length > 1) {
        (headers as any)[h[0].toLowerCase()] = h
          .slice(1)
          .join(':')
          .trim();
      }
    });
  return new GenericResponse<string>(
    xhr.status,
    headers,
    xhr.responseText,
    url
  );
}
module.exports = doRequest;
module.exports.default = doRequest;
module.exports.FormData = fd;