| 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246 |
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
63×
63×
63×
63×
63×
1×
62×
2×
1×
1×
1×
1×
63×
6×
1×
1×
5×
63×
63×
63×
5×
58×
5×
53×
5×
63×
63×
1×
252×
63×
63×
61×
1×
61×
1×
1×
2×
1×
1×
61×
61×
61×
61×
61×
61×
61×
61×
61×
61×
61×
61×
61×
61×
61×
61×
61×
4×
4×
4×
57×
4×
4×
4×
53×
63×
1×
4×
4×
63×
2×
2×
2×
2×
63×
63×
63×
63×
63×
63×
63×
63×
63×
1×
3×
1×
1×
4×
50×
1×
| /* najax
* jquery ajax-stye http requests in node
* https://github.com/alanclarke/najax
*/
var https = require('https')
var http = require('http')
var querystring = require('querystring')
var url = require('url')
var zlib = require('zlib')
var $ = require('jquery-deferred')
var _ = require('lodash')
var parseOptions = require('./parse-options')
var defaults = {
method: 'GET',
rejectUnauthorized: true,
processData: true,
data: '',
contentType: 'application/x-www-form-urlencoded',
headers: {},
setRequestHeader: function (name, value) {
this.headers[name] = value
}
}
/*
method overloading, can use:
-function(url, opts, callback) or
-function(url, callback)
-function(opts)
*/
function najax (uri, options, callback) {
var dfd = new $.Deferred()
var o = _.extend({}, defaults, parseOptions(uri, options, callback))
var l = url.parse(o.url)
var ssl = l.protocol.indexOf('https') === 0
// DATA
// Per jquery docs / source: encoding is only done
// if processData is true (defaults to true)
// and the data is not already a string
// https://github.com/jquery/jquery/blob/master/src/ajax.js#L518
if (o.data && o.processData && o.method === 'GET') {
o.data = querystring.stringify(o.data)
} else if (o.data && o.processData && typeof o.data !== 'string' && o.method !== 'GET') {
switch (o.contentType) {
case 'application/json':
o.data = JSON.stringify(o.data)
break
case 'application/x-www-form-urlencoded':
o.data = querystring.stringify(o.data)
break
default:
o.data = String(o.data)
}
}
/* if get, use querystring method for data */
if (o.data) {
if (o.method === 'GET') {
Iif (l.search) {
l.search += '&' + o.data
} else {
l.search = '?' + o.data
}
} else {
/* set data content type */
o.headers = _.extend({
'Content-Type': o.contentType + ';charset=utf-8',
'Content-Length': Buffer.byteLength(o.data)
}, o.headers)
}
}
if (o.beforeSend) o.beforeSend(o)
options = {
host: l.hostname,
path: l.pathname + (l.search || ''),
method: o.method,
port: Number(l.port) || (ssl ? 443 : 80),
headers: o.headers,
rejectUnauthorized: o.rejectUnauthorized
}
// AUTHENTICATION
/* add authentication to http request */
if (l.auth) {
options.auth = l.auth
} else if (o.username && o.password) {
options.auth = o.username + ':' + o.password
} else if (o.auth) {
options.auth = o.auth
}
_.extend(options, _.pick(o, ['auth', 'agent']))
/* for debugging, method to get options and return */
Iif (o.getopts) {
var getopts = [ssl, options, o.data || false, o.success || false, o.error || false]
return getopts
}
// REQUEST
function notImplemented (name) {
return function () {
console.error('najax: method jqXHR."' + name + '" not implemented')
console.trace()
}
}
var jqXHR = {
readyState: 0,
status: 0,
statusText: 'error', // one of: "success", "notmodified", "error", "timeout", "abort", or "parsererror"
setRequestHeader: notImplemented('setRequestHeader'),
getAllResponseHeaders: notImplemented('getAllResponseHeaders'),
statusCode: notImplemented('statusCode'),
abort: notImplemented('abort')
}
var req = (ssl ? https : http).request(options, function (res) {
// Allow getting Response Headers from the XMLHTTPRequest object
dfd.getResponseHeader = jqXHR.getResponseHeader = function getResponseHeader (header) {
return res.headers[header.toLowerCase()]
}
dfd.getAllResponseHeaders = jqXHR.getAllResponseHeaders = function getAllResponseHeaders () {
var headers = []
for (var key in res.headers) {
headers.push(key + ': ' + res.headers[key])
}
return headers.join('\n')
}
function dataHandler (data) {
jqXHR.responseText = data
Iif (o.dataType === 'json' || o.dataType === 'jsonp') {
// replace control characters
try {
data = JSON.parse(data.replace(/[\cA-\cZ]/gi, ''))
} catch (e) {
return onError(e)
}
}
var statusCode = res.statusCode
jqXHR.statusText = 'success'
Iif (statusCode === 204 || options.method === 'HEAD') {
jqXHR.statusText = 'nocontent'
} else Iif (statusCode === 304) {
jqXHR.statusText = 'notmodified'
}
// Determine if successful
// (per https://github.com/jquery/jquery/blob/master/src/ajax.js#L679)
var isSuccess = statusCode >= 200 && statusCode < 300 || statusCode === 304
// Set readyState
jqXHR.readyState = statusCode > 0 ? 4 : 0
jqXHR.status = statusCode
Eif (isSuccess) {
// success, statusText, jqXHR
dfd.resolve(data, jqXHR.statusText, jqXHR)
} else {
// jqXHR, statusText, error
// When an HTTP error occurs, errorThrown receives the textual portion of the
// HTTP status, such as "Not Found" or "Internal Server Error."
jqXHR.statusText = 'error'
onError(new Error(http.STATUS_CODES[statusCode]))
}
}
var chunks = []
res.on('data', function (chunk) { chunks.push(chunk) })
res.on('end', function () {
var buffer = Buffer.concat(chunks)
var encoding = res.headers['content-encoding']
if (encoding === 'gzip') {
zlib.gunzip(buffer, function (err, buffer) {
Iif (err) {
onError(err)
} else {
dataHandler(buffer.toString())
}
})
} else if (encoding === 'deflate') {
zlib.inflate(buffer, function (err, buffer) {
Iif (err) {
onError(err)
} else {
dataHandler(buffer.toString())
}
})
} else {
dataHandler(buffer.toString())
}
})
})
// ERROR
req.on('error', onError)
function onError (e) {
// Set data for the fake xhr object
Iif (jqXHR.statusText === 'error') jqXHR.responseText = e.stack
// jqXHR, statusText, error
dfd.reject(jqXHR, jqXHR.statusText, e)
}
// SET TIMEOUT
if (o.timeout && o.timeout > 0) {
req.setTimeout(o.timeout, function () {
req.abort()
jqXHR.statusText = 'timeout'
onError(new Error('timeout'))
})
}
// SEND DATA
if (o.method !== 'GET' && o.data) req.write(o.data, 'utf-8')
req.end()
// DEFERRED
dfd.done(o.success)
dfd.done(o.complete)
dfd.fail(o.error)
dfd.fail(o.complete)
dfd.success = dfd.done
dfd.error = dfd.fail
return dfd
}
najax.defaults = function defaults (opts) {
return _.extend(defaults, opts)
}
/* auto rest interface go! */
_.each(['GET', 'POST', 'PUT', 'DELETE'], handleMethod)
function handleMethod (method) {
najax[method.toLowerCase()] = function methodHandler (uri, options, callback) {
return najax(_.extend(parseOptions(uri, options, callback), { method: method }))
}
}
module.exports = najax
|