/
http-proxy-middleware.spec.ts
457 lines (396 loc) · 14.6 KB
/
http-proxy-middleware.spec.ts
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
import { createProxyMiddleware, createApp, createAppWithPath } from './_utils';
import * as request from 'supertest';
import { Mockttp, getLocal, CompletedRequest } from 'mockttp';
import * as bodyParser from 'body-parser';
describe('E2E http-proxy-middleware', () => {
describe('http-proxy-middleware creation', () => {
it('should create a middleware', () => {
const middleware = createProxyMiddleware('/api', {
target: `http://localhost:8000`,
});
expect(typeof middleware).toBe('function');
});
});
describe('context matching', () => {
describe('do not proxy', () => {
let isSkipped;
beforeEach(() => {
isSkipped = false;
let middleware;
const mockReq = { url: '/foo/bar', originalUrl: '/foo/bar' };
const mockRes = {};
const mockNext = () => {
// mockNext will be called when request is not proxied
isSkipped = true;
};
middleware = createProxyMiddleware('/api', {
target: `http://localhost:8000`,
});
middleware(mockReq, mockRes, mockNext);
});
it('should not proxy requests when request url does not match context', () => {
expect(isSkipped).toBe(true);
});
});
});
describe('http-proxy-middleware in actual server', () => {
let mockTargetServer: Mockttp;
let agent: request.SuperTest<request.Test>;
beforeEach(async () => {
mockTargetServer = getLocal();
await mockTargetServer.start();
});
afterEach(async () => {
await mockTargetServer.stop();
});
describe('basic setup, requests to target', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware('/api', {
target: `http://localhost:${mockTargetServer.port}`,
})
)
);
});
it('should have response body: "HELLO WEB"', async () => {
await mockTargetServer.get('/api').thenReply(200, 'HELLO WEB');
const response = await agent.get(`/api`).expect(200);
expect(response.text).toBe('HELLO WEB');
});
it('should have proxied the uri-path and uri-query, but not the uri-hash', async () => {
await mockTargetServer
.get('/api/b/c/dp')
.withExactQuery('?q=1&r=[2,3]')
.thenReply(200, 'OK');
const response = await request(`http://localhost:${mockTargetServer.port}`)
.get(`/api/b/c/dp?q=1&r=[2,3]#s`)
.expect(200);
expect(response.text).toBe('OK');
});
});
describe('basic setup with configured body-parser', () => {
it('should proxy request body from form', async () => {
agent = request(
createApp(
bodyParser.urlencoded({ extended: false }),
createProxyMiddleware('/api', {
target: `http://localhost:${mockTargetServer.port}`,
})
)
);
await mockTargetServer.post('/api').thenCallback((req) => {
expect(req.body.text).toBe('foo=bar&bar=baz');
return { status: 200 };
});
await agent.post('/api').send('foo=bar').send('bar=baz').expect(200);
});
it('should proxy request body from json', async () => {
agent = request(
createApp(
bodyParser.json(),
createProxyMiddleware('/api', {
target: `http://localhost:${mockTargetServer.port}`,
})
)
);
await mockTargetServer.post('/api').thenCallback((req) => {
expect(req.body.json).toEqual({ foo: 'bar', bar: 'baz' });
return { status: 200 };
});
await agent.post('/api').send({ foo: 'bar', bar: 'baz' }).expect(200);
});
});
describe('custom context matcher/filter', () => {
it('should have response body: "HELLO WEB"', async () => {
const filter = (path, req) => {
return true;
};
agent = request(
createApp(
createProxyMiddleware(filter, {
target: `http://localhost:${mockTargetServer.port}`,
})
)
);
await mockTargetServer.get('/api/b/c/d').thenReply(200, 'HELLO WEB');
const response = await agent.get(`/api/b/c/d`).expect(200);
expect(response.text).toBe('HELLO WEB');
});
it('should not proxy when filter returns false', async () => {
const filter = (path, req) => {
return false;
};
agent = request(
createApp(
createProxyMiddleware(filter, {
target: `http://localhost:${mockTargetServer.port}`,
})
)
);
await mockTargetServer.get('/api/b/c/d').thenReply(200, 'HELLO WEB');
const response = await agent.get(`/api/b/c/d`).expect(404);
expect(response.status).toBe(404);
});
});
describe('multi path', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware(['/api', '/ajax'], {
target: `http://localhost:${mockTargetServer.port}`,
})
)
);
});
it('should proxy to path /api', async () => {
await mockTargetServer.get(/\/api\/.+/).thenReply(200, 'HELLO /API');
const response = await agent.get(`/api/b/c/d`).expect(200);
expect(response.text).toBe('HELLO /API');
});
it('should proxy to path /ajax', async () => {
await mockTargetServer.get(/\/ajax\/.+/).thenReply(200, 'HELLO /AJAX');
const response = await agent.get(`/ajax/b/c/d`).expect(200);
expect(response.text).toBe('HELLO /AJAX');
});
it('should not proxy with no matching path', async () => {
const response = await agent.get(`/lorum/ipsum`).expect(404);
expect(response.status).toBe(404);
});
});
describe('wildcard path matching', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware('/api/**', {
target: `http://localhost:${mockTargetServer.port}`,
})
)
);
});
it('should proxy to path', async () => {
await mockTargetServer.get(/\/api\/.+/).thenReply(200, 'HELLO /api');
const response = await agent.get(`/api/b/c/d`).expect(200);
expect(response.text).toBe('HELLO /api');
});
});
describe('multi glob wildcard path matching', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware(['**/*.html', '!**.json'], {
target: `http://localhost:${mockTargetServer.port}`,
})
)
);
});
it('should proxy to paths ending with *.html', async () => {
await mockTargetServer.get(/.+html$/).thenReply(200, 'HELLO .html');
const response = await agent.get(`/api/some/endpoint/index.html`).expect(200);
expect(response.text).toBe('HELLO .html');
});
it('should not proxy to paths ending with *.json', async () => {
await mockTargetServer.get(/.+json$/).thenReply(200, 'HELLO .html');
const response = await agent.get(`/api/some/endpoint/data.json`).expect(404);
expect(response.status).toBe(404);
});
});
describe('option.headers - additional request headers', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware('/api', {
target: `http://localhost:${mockTargetServer.port}`,
headers: { host: 'foobar.dev' },
})
)
);
});
it('should send request header "host" to target server', async () => {
let completedRequest: CompletedRequest;
await mockTargetServer.get().thenCallback((req) => {
completedRequest = req;
return { statusCode: 200, body: 'OK' };
});
const response = await agent.get(`/api/some/endpoint/index.html`).expect(200);
expect(response.text).toBe('OK');
expect(completedRequest.headers.host).toBe('foobar.dev');
});
});
describe('option.onError - with default error handling', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware({
target: `http://localhost:666`, // unreachable host on port:666
})
)
);
});
it('should handle errors when host is not reachable', async () => {
const response = await agent.get(`/api/some/endpoint`).expect(504);
expect(response.status).toBe(504);
});
});
describe('option.onError - custom error handling', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware({
target: `http://localhost:666`, // unreachable host on port:666
onError(err, req, res) {
if (err) {
res.writeHead(418); // different error code
res.end("I'm a teapot"); // no response body
}
},
})
)
);
});
it('should respond with custom http status code', async () => {
const response = await agent.get(`/api/some/endpoint`).expect(418);
expect(response.status).toBe(418);
});
it('should respond with custom status message', async () => {
const response = await agent.get(`/api/some/endpoint`).expect(418);
expect(response.text).toBe("I'm a teapot");
});
});
describe('option.onProxyRes', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware('/api', {
target: `http://localhost:${mockTargetServer.port}`,
onProxyRes(proxyRes, req, res) {
// tslint:disable-next-line: no-string-literal
proxyRes['headers']['x-added'] = 'foobar'; // add custom header to response
// tslint:disable-next-line: no-string-literal
delete proxyRes['headers']['x-removed'];
},
})
)
);
});
it('should add `x-added` as custom header to response"', async () => {
await mockTargetServer.get().thenReply(200, 'HELLO .html');
const response = await agent.get(`/api/some/endpoint/index.html`).expect(200);
expect(response.header['x-added']).toBe('foobar');
});
it('should remove `x-removed` field from response header"', async () => {
await mockTargetServer.get().thenCallback((req) => {
return {
statusCode: 200,
headers: {
'x-removed': 'this should be removed',
},
};
});
const response = await agent.get(`/api/some/endpoint/index.html`).expect(200);
expect(response.header['x-removed']).toBeUndefined();
});
});
describe('option.onProxyReq', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware('/api', {
target: `http://localhost:${mockTargetServer.port}`,
onProxyReq(proxyReq, req, res) {
proxyReq.setHeader('x-added', 'added-from-hpm'); // add custom header to request
},
})
)
);
});
it('should add `x-added` as custom header to request"', async () => {
let completedRequest: CompletedRequest;
await mockTargetServer.get().thenCallback((req) => {
completedRequest = req;
return { statusCode: 200 };
});
await agent.get(`/api/foo/bar`).expect(200);
expect(completedRequest.headers['x-added']).toBe('added-from-hpm');
});
});
describe('option.pathRewrite', () => {
beforeEach(() => {
agent = request(
createApp(
createProxyMiddleware({
target: `http://localhost:${mockTargetServer.port}`,
pathRewrite: {
'^/api': '/rest',
'^/remove': '',
},
})
)
);
});
it('should have rewritten path from "/api/foo/bar" to "/rest/foo/bar"', async () => {
await mockTargetServer.get('/rest/foo/bar').thenReply(200, 'HELLO /rest/foo/bar');
const response = await agent.get(`/api/foo/bar`).expect(200);
expect(response.text).toBe('HELLO /rest/foo/bar');
});
it('should have removed path from "/remove/api/lipsum" to "/api/lipsum"', async () => {
await mockTargetServer.get('/api/lipsum').thenReply(200, 'HELLO /api/lipsum');
const response = await agent.get(`/remove/api/lipsum`).expect(200);
expect(response.text).toBe('HELLO /api/lipsum');
});
});
describe('shorthand usage', () => {
beforeEach(() => {
agent = request(
createApp(createProxyMiddleware(`http://localhost:${mockTargetServer.port}/api`))
);
});
it('should have proxy with shorthand configuration', async () => {
await mockTargetServer.get('/api/foo/bar').thenReply(200, 'HELLO /api/foo/bar');
const response = await agent.get(`/api/foo/bar`).expect(200);
expect(response.text).toBe('HELLO /api/foo/bar');
});
});
describe('express with path + proxy', () => {
beforeEach(() => {
agent = request(
createAppWithPath(
'/api',
createProxyMiddleware({ target: `http://localhost:${mockTargetServer.port}` })
)
);
});
it('should proxy to target with the baseUrl', async () => {
await mockTargetServer.get('/api/foo/bar').thenReply(200, 'HELLO /api/foo/bar');
const response = await agent.get(`/api/foo/bar`).expect(200);
expect(response.text).toBe('HELLO /api/foo/bar');
});
});
describe('option.logLevel & option.logProvider', () => {
let logMessage;
beforeEach(() => {
const customLogger = (message) => {
logMessage = message;
};
agent = request(
createApp(
createProxyMiddleware('/api', {
target: `http://localhost:${mockTargetServer.port}`,
logLevel: 'info',
logProvider(provider) {
return { ...provider, debug: customLogger, info: customLogger };
},
})
)
);
});
it('should have logged messages', async () => {
await mockTargetServer.get('/api/foo/bar').thenReply(200);
await agent.get(`/api/foo/bar`).expect(200);
expect(logMessage).toMatchInlineSnapshot(
`"[HPM] Proxy created: /api -> http://localhost:8000"`
);
});
});
});
});