-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonp.js
49 lines (38 loc) · 1.19 KB
/
jsonp.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
var middleware = require('./middleware')
var randomString = require('random-string')
var mergeQueryString = require('../mergeQueryString')
function randomGlobal (value) {
var name
do {
name = '_' + randomString({ length: 20 })
} while (typeof window[name] !== 'undefined')
window[name] = value
return name
}
module.exports = middleware('jsonp', function (request, next) {
var jsonp = request.options.jsonp
if (jsonp) {
request.options.querystring = request.options.querystring || {}
return new Promise(function (resolve, reject) {
var callbackName = randomGlobal(function (v) {
delete window[callbackName]
document.head.removeChild(script)
resolve({
statusCode: 200,
headers: {},
body: v
})
})
request.options.querystring[jsonp] = callbackName
mergeQueryString(request)
var script = document.createElement('script')
script.type = 'text/javascript'
script.src = request.url
script.onerror = function () {
reject(new Error('could not load script tag for JSONP request: ' + request.url))
}
document.head.appendChild(script)
})
}
return next()
})