-
Notifications
You must be signed in to change notification settings - Fork 495
/
Copy pathxhr-proxy.js
269 lines (238 loc) · 7.4 KB
/
xhr-proxy.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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/*
* author: wendux
* email: [email protected]
* source code: https://github.com/wendux/Ajax-hook
*/
import {hook, configEvent, events} from "./xhr-hook";
var eventLoad = events[0],
eventLoadEnd = events[1],
eventTimeout = events[2],
eventError = events[3],
eventReadyStateChange = events[4],
eventAbort = events[5];
var prototype = 'prototype';
export function proxy(proxy, win) {
win = win || window;
return proxyAjax(proxy, win);
}
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function getEventTarget(xhr) {
return xhr.watcher || (xhr.watcher = document.createElement('a'));
}
function triggerListener(xhr, name) {
var xhrProxy = xhr.getProxy();
var callback = 'on' + name + '_';
var event = configEvent({type: name}, xhrProxy);
xhrProxy[callback] && xhrProxy[callback](event);
var evt;
if (typeof(Event) === 'function') {
evt = new Event(name, {bubbles: false});
} else {
// https://stackoverflow.com/questions/27176983/dispatchevent-not-working-in-ie11
evt = document.createEvent('Event');
evt.initEvent(name, false, true);
}
getEventTarget(xhr).dispatchEvent(evt);
}
function Handler(xhr) {
this.xhr = xhr;
this.xhrProxy = xhr.getProxy();
}
Handler[prototype] = Object.create({
resolve: function resolve(response) {
var xhrProxy = this.xhrProxy;
var xhr = this.xhr;
xhrProxy.readyState = 4;
xhr.resHeader = response.headers;
xhrProxy.response = xhrProxy.responseText = response.response;
xhrProxy.statusText = response.statusText;
xhrProxy.status = response.status;
triggerListener(xhr, eventReadyStateChange);
triggerListener(xhr, eventLoad);
triggerListener(xhr, eventLoadEnd);
},
reject: function reject(error) {
this.xhrProxy.status = 0;
triggerListener(this.xhr, error.type);
triggerListener(this.xhr, eventLoadEnd);
}
});
function makeHandler(next) {
function sub(xhr) {
Handler.call(this, xhr);
}
sub[prototype] = Object.create(Handler[prototype]);
sub[prototype].next = next
return sub;
}
var RequestHandler = makeHandler(function (rq) {
var xhr = this.xhr;
rq = rq || xhr.config;
xhr.withCredentials = rq.withCredentials;
xhr.open(rq.method, rq.url, rq.async !== false, rq.user, rq.password);
for (var key in rq.headers) {
xhr.setRequestHeader(key, rq.headers[key]);
}
xhr.send(rq.body);
});
var ResponseHandler = makeHandler(function (response) {
this.resolve(response);
});
var ErrorHandler = makeHandler(function (error) {
this.reject(error);
});
function proxyAjax(proxy, win) {
var onRequest = proxy.onRequest,
onResponse = proxy.onResponse,
onError = proxy.onError;
function handleResponse(xhr, xhrProxy) {
var handler = new ResponseHandler(xhr);
var responseType = xhrProxy.responseType;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
xhrProxy.responseText : xhrProxy.response;
var ret = {
response: responseData, //ie9
status: xhrProxy.status,
statusText: xhrProxy.statusText,
config: xhr.config,
headers: xhr.resHeader || xhr.getAllResponseHeaders().split('\r\n').reduce(function (ob, str) {
if (str === "") return ob;
var m = str.split(":");
ob[m.shift()] = trim(m.join(':'));
return ob;
}, {})
};
if (!onResponse) return handler.resolve(ret);
onResponse(ret, handler);
}
function onerror(xhr, xhrProxy, error, errorType) {
var handler = new ErrorHandler(xhr);
error = {config: xhr.config, error: error, type: errorType};
if (onError) {
onError(error, handler);
} else {
handler.next(error);
}
}
function preventXhrProxyCallback() {
return true;
}
function errorCallback(errorType) {
return function (xhr, e) {
onerror(xhr, this, e, errorType);
return true;
}
}
function stateChangeCallback(xhr, xhrProxy) {
var config = xhrProxy ? xhrProxy.config : null;
if (config && xhr && config.xhr === xhr) {
if (xhr.readyState === 4 && xhr.status !== 0) {
handleResponse(xhr, xhrProxy);
} else if (xhr.readyState !== 4) {
triggerListener(xhr, eventReadyStateChange);
}
if (xhr.readyState === XMLHttpRequest.DONE) {
config.xhr = null;
xhr['on' + eventReadyStateChange] = null;
}
}
return true;
}
var { originXhr, unHook } = hook({
onload: preventXhrProxyCallback,
onloadend: preventXhrProxyCallback,
onerror: errorCallback(eventError),
ontimeout: errorCallback(eventTimeout),
onabort: errorCallback(eventAbort),
onreadystatechange: function (xhr) {
return stateChangeCallback(xhr, this);
},
open: function open(args, xhr) {
var _this = this;
var config = xhr.config = {headers: {}};
config.method = args[0];
config.url = args[1];
config.async = args[2];
config.user = args[3];
config.password = args[4];
Object.defineProperty(config, 'xhr', {
get() {
return xhr; // xhr wil be set to null after xhr.readyState === XMLHttpRequest.DONE
},
set(nv) {
if (nv === null) xhr = null;
return true;
},
enumerable: false,
configurable: true
});
// config.xhr = xhr;
var evName = 'on' + eventReadyStateChange;
if (!xhr[evName]) {
xhr[evName] = function () {
return stateChangeCallback(this, _this);
};
}
// 如果有请求拦截器,则在调用onRequest后再打开链接。因为onRequest最佳调用时机是在send前,
// 所以我们在send拦截函数中再手动调用open,因此返回true阻止xhr.open调用。
//
// 如果没有请求拦截器,则不用阻断xhr.open调用
if (onRequest) return true;
},
send: function (args, xhr) {
var config = xhr.config
config.withCredentials = xhr.withCredentials
config.body = args[0];
if (onRequest) {
// In 'onRequest', we may call XHR's event handler, such as `xhr.onload`.
// However, XHR's event handler may not be set until xhr.send is called in
// the user's code, so we use `setTimeout` to avoid this situation
var req = function () {
onRequest(config, new RequestHandler(xhr));
}
config.async === false ? req() : setTimeout(req)
return true;
}
},
setRequestHeader: function (args, xhr) {
// Collect request headers
xhr.config.headers[args[0].toLowerCase()] = args[1];
if (onRequest) return true;
},
addEventListener: function (args, xhr) {
var _this = this;
if (events.indexOf(args[0]) !== -1) {
var handler = args[1];
getEventTarget(xhr).addEventListener(args[0], function (e) {
var event = configEvent(e, _this);
event.type = args[0];
event.isTrusted = true;
handler.call(_this, event);
});
return true;
}
},
getAllResponseHeaders: function (_, xhr) {
var headers = xhr.resHeader
if (headers) {
var header = "";
for (var key in headers) {
header += key + ': ' + headers[key] + '\r\n';
}
return header;
}
},
getResponseHeader: function (args, xhr) {
var headers = xhr.resHeader
if (headers) {
return headers[(args[0] || '').toLowerCase()];
}
}
}, win);
return {
originXhr,
unProxy: unHook
}
}