forked from yields/send-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (81 loc) · 1.71 KB
/
index.js
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
92
93
94
95
96
97
98
99
100
/**
* Module dependencies.
*/
var encode = require('base64-encode');
var cors = require('has-cors');
var jsonp = require('jsonp');
var JSON = require('json');
/**
* Expose `send`
*/
exports = module.exports = cors
? json
: base64;
/**
* Expose `callback`
*/
exports.callback = 'callback';
/**
* Expose `prefix`
*/
exports.prefix = 'data';
/**
* Expose `json`.
*/
exports.json = json;
/**
* Expose `base64`.
*/
exports.base64 = base64;
/**
* Expose `type`
*/
exports.type = cors
? 'xhr'
: 'jsonp';
/**
* Send the given `obj` to `url` with `fn(err, req)`.
*
* @param {String} url
* @param {Object} obj
* @param {Object} headers
* @param {Object} props
* @param {Function} fn
* @api private
*/
function json(url, obj, headers, props, fn){
if (3 == arguments.length) fn = headers, headers = {}, props = {};
if (4 == arguments.length) fn = props, props = {};
var req = new XMLHttpRequest;
req.onerror = fn;
req.onreadystatechange = done;
req.open('POST', url, true);
for (var p in props) req[p] = props[p];
for (var k in headers) req.setRequestHeader(k, headers[k]);
req.send(JSON.stringify(obj));
function done(){
if (4 == req.readyState) return fn(null, req);
}
}
/**
* Send the given `obj` to `url` with `fn(err, req)`.
*
* @param {String} url
* @param {Object} obj
* @param {Function} fn
* @api private
*/
function base64(url, obj, _, fn){
if (3 == arguments.length) fn = _;
var prefix = exports.prefix;
obj = encode(JSON.stringify(obj));
obj = encodeURIComponent(obj);
url += '?' + prefix + '=' + obj;
jsonp(url, { param: exports.callback }, function(err, obj){
if (err) return fn(err);
fn(null, {
url: url,
body: obj
});
});
}