UNPKG

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