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