1 | "use strict";
|
2 | exports.__esModule = true;
|
3 | var handle_qs_js_1 = require("then-request/lib/handle-qs.js");
|
4 | var GenericResponse = require("http-response-object");
|
5 | var fd = FormData;
|
6 | exports.FormData = fd;
|
7 | function doRequest(method, url, options) {
|
8 | var xhr = new XMLHttpRequest();
|
9 |
|
10 | if (typeof method !== 'string') {
|
11 | throw new TypeError('The method must be a string.');
|
12 | }
|
13 | if (url && typeof url === 'object') {
|
14 | url = url.href;
|
15 | }
|
16 | if (typeof url !== 'string') {
|
17 | throw new TypeError('The URL/path must be a string.');
|
18 | }
|
19 | if (options === null || options === undefined) {
|
20 | options = {};
|
21 | }
|
22 | if (typeof options !== 'object') {
|
23 | throw new TypeError('Options must be an object (or null).');
|
24 | }
|
25 | method = method.toUpperCase();
|
26 | options.headers = options.headers || {};
|
27 |
|
28 | var match;
|
29 | var crossDomain = !!((match = /^([\w-]+:)?\/\/([^\/]+)/.exec(url)) && match[2] != location.host);
|
30 | if (!crossDomain)
|
31 | options.headers['X-Requested-With'] = 'XMLHttpRequest';
|
32 |
|
33 | if (options.qs) {
|
34 | url = handle_qs_js_1["default"](url, options.qs);
|
35 | }
|
36 |
|
37 | if (options.json) {
|
38 | options.body = JSON.stringify(options.json);
|
39 | options.headers['content-type'] = 'application/json';
|
40 | }
|
41 | if (options.form) {
|
42 | options.body = options.form;
|
43 | }
|
44 |
|
45 | xhr.open(method, url, false);
|
46 | for (var name in options.headers) {
|
47 | xhr.setRequestHeader(name.toLowerCase(), '' + options.headers[name]);
|
48 | }
|
49 |
|
50 | xhr.send(options.body ? options.body : null);
|
51 | var headers = {};
|
52 | xhr
|
53 | .getAllResponseHeaders()
|
54 | .split('\r\n')
|
55 | .forEach(function (header) {
|
56 | var h = header.split(':');
|
57 | if (h.length > 1) {
|
58 | headers[h[0].toLowerCase()] = h
|
59 | .slice(1)
|
60 | .join(':')
|
61 | .trim();
|
62 | }
|
63 | });
|
64 | return new GenericResponse(xhr.status, headers, xhr.responseText, url);
|
65 | }
|
66 | exports["default"] = doRequest;
|
67 | module.exports = doRequest;
|
68 | module.exports["default"] = doRequest;
|
69 | module.exports.FormData = fd;
|