UNPKG

3.3 kBJavaScriptView Raw
1var chalk = require('chalk');
2var historyApiFallback = require('connect-history-api-fallback');
3var httpProxyMiddleware = require('http-proxy-middleware');
4
5// We need to provide a custom onError function for httpProxyMiddleware.
6// It allows us to log custom error messages on the console.
7function 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 // And immediately send the proper error response to the client.
21 // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
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// `proxy` lets you to specify a fallback server during development.
32// Every unrecognized request will be forwarded to it.
33function addProxyModdileware(devServer, config) {
34 if (config && config.proxy) {
35 var target = config.proxy.target;
36 var publicPath = config.output.public.replace('/', '');
37
38 // Otherwise, if proxy is specified, we will let it handle any request.
39 // There are a few exceptions which we won't send to the proxy:
40 // - /index.html (served as HTML5 history API fallback)
41 // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
42 // - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
43 // Tip: use https://jex.im/regulex/ to visualize the regex
44 var mayProxy = new RegExp('^(?!\\/(index\\.html$|.*\\.hot-update\\.json$|sockjs-node\\/' + (publicPath.length > 0 ? '|' + publicPath + '.*' : '') + ')).*$');
45
46 // Pass the scope regex both to Express and to the middleware for proxying
47 // of both HTTP and WebSockets to work without false positives.
48 var hpm = httpProxyMiddleware(function (pathname) {
49 return mayProxy.test(pathname);
50 }, Object.assign({
51 logLevel: 'silent',
52 onProxyReq: function(proxyReq, req, res) {
53 // Browers may send Origin headers even with same-origin
54 // requests. To prevent CORS issues, we have to change
55 // the Origin to match the target URL.
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 // Listen for the websocket 'upgrade' event and upgrade the connection.
69 // If this is not done, httpProxyMiddleware will not try to upgrade until
70 // an initial plain HTTP request is made.
71 devServer.listeningApp.on('upgrade', hpm.upgrade);
72 }
73 // Finally, by now we have certainly resolved the URL.
74 // It may be /index.html, so let the dev server try serving it again.
75 devServer.use(devServer.middleware);
76}
77
78module.exports = addProxyModdileware;