1 | var chalk = require('chalk');
|
2 | var historyApiFallback = require('connect-history-api-fallback');
|
3 | var httpProxyMiddleware = require('http-proxy-middleware');
|
4 |
|
5 |
|
6 |
|
7 | function onProxyError(proxy) {
|
8 | return function(err, req, res) {
|
9 | var host = req.headers && req.headers.host;
|
10 | console.log(
|
11 | chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
|
12 | ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
|
13 | );
|
14 | console.log(
|
15 | 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
|
16 | chalk.cyan(err.code) + ').'
|
17 | );
|
18 | console.log();
|
19 |
|
20 |
|
21 |
|
22 | if (res.writeHead && !res.headersSent) {
|
23 | res.writeHead(500);
|
24 | }
|
25 | res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
|
26 | host + ' to ' + proxy + ' (' + err.code + ').'
|
27 | );
|
28 | };
|
29 | }
|
30 |
|
31 |
|
32 |
|
33 | function addProxyModdileware(devServer, config) {
|
34 | if (config && config.proxy) {
|
35 | var target = config.proxy.target;
|
36 | var publicPath = config.output.public.replace('/', '');
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | var mayProxy = new RegExp('^(?!\\/(index\\.html$|.*\\.hot-update\\.json$|sockjs-node\\/' + (publicPath.length > 0 ? '|' + publicPath + '.*' : '') + ')).*$');
|
45 |
|
46 |
|
47 |
|
48 | var hpm = httpProxyMiddleware(function (pathname) {
|
49 | return mayProxy.test(pathname);
|
50 | }, Object.assign({
|
51 | logLevel: 'silent',
|
52 | onProxyReq: function(proxyReq, req, res) {
|
53 |
|
54 |
|
55 |
|
56 | if (proxyReq.getHeader('origin')) {
|
57 | proxyReq.setHeader('origin', target);
|
58 | }
|
59 | },
|
60 | onError: onProxyError(target),
|
61 | secure: false,
|
62 | changeOrigin: true,
|
63 | ws: true,
|
64 | xfwd: true
|
65 | }, config.proxy));
|
66 | devServer.use(mayProxy, hpm);
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | devServer.listeningApp.on('upgrade', hpm.upgrade);
|
72 | }
|
73 |
|
74 |
|
75 | devServer.use(devServer.middleware);
|
76 | }
|
77 |
|
78 | module.exports = addProxyModdileware;
|