forked from Experience-Monks/xhr-request
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (49 loc) · 1.44 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
var queryString = require('query-string')
var setQuery = require('url-set-query')
var assign = require('object-assign')
var ensureHeader = require('./lib/ensure-header.js')
// this is replaced in the browser
var request = require('./lib/request.js')
var mimeTypeJson = 'application/json'
var noop = function () {}
module.exports = xhrRequest
function xhrRequest (url, opt, cb) {
if (!url || typeof url !== 'string') {
throw new TypeError('must specify a URL')
}
if (typeof opt === 'function') {
cb = opt
opt = {}
}
if (cb && typeof cb !== 'function') {
throw new TypeError('expected cb to be undefined or a function')
}
cb = cb || noop
opt = opt || {}
var defaultResponse = opt.json ? 'json' : 'text'
opt = assign({ responseType: defaultResponse }, opt)
var headers = opt.headers || {}
var method = (opt.method || 'GET').toUpperCase()
var query = opt.query
if (query) {
if (typeof query !== 'string') {
query = queryString.stringify(query)
}
url = setQuery(url, query)
}
// allow json response
if (opt.responseType === 'json') {
ensureHeader(headers, 'Accept', mimeTypeJson)
}
// if body content is json
if (opt.json && method !== 'GET' && method !== 'HEAD') {
ensureHeader(headers, 'Content-Type', mimeTypeJson)
opt.body = JSON.stringify(opt.body)
}
opt.method = method
opt.url = url
opt.headers = headers
delete opt.query
delete opt.json
return request(opt, cb)
}