UNPKG

2.25 kBJavaScriptView Raw
1"use strict";
2exports.__esModule = true;
3var handle_qs_js_1 = require("then-request/lib/handle-qs.js");
4var GenericResponse = require("http-response-object");
5var fd = FormData;
6exports.FormData = fd;
7function doRequest(method, url, options) {
8 var xhr = new XMLHttpRequest();
9 // check types of arguments
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 // handle cross domain
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 // handle query string
33 if (options.qs) {
34 url = handle_qs_js_1["default"](url, options.qs);
35 }
36 // handle json body
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 // method, url, async
45 xhr.open(method, url, false);
46 for (var name in options.headers) {
47 xhr.setRequestHeader(name.toLowerCase(), '' + options.headers[name]);
48 }
49 // avoid sending empty string (#319)
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}
66exports["default"] = doRequest;
67module.exports = doRequest;
68module.exports["default"] = doRequest;
69module.exports.FormData = fd;