Webpack和Koa2代理WebSocket

相关运行环境:

mac os: 10.14.5 (18F132)

chrome: 81.0.4044.122

Node:v10.16.1

npm: v6.14.4

Webpack-dev-server: v3.9.0

http-proxy-middleware: 1.0.3

Koa2-connect: 1.0.2

koa: 2.7.0

webpack代理

webpack-dev-server配置:

webpackConfig.devServer = {
    host: '127.0.0.1',
    disableHostCheck: true,
    https: true,
    proxy: {
        '/socket': {
            target: WS_URL,
            changeOrigin: true,
            pathRewrite: {
                '^/socket': ''
            },
            ws: true,
            secure: false
        }
    }
};

WebSocket实例URL:
踩坑:webpackDevServer https环境下只能代理wss协议,如果这里改成ws协议代理将会不起效果,并且不会出现任何错误提示!

url: 'wss://' + window.location.host + '/socket/ws';

koa2代理

const koaConnect = require('koa2-connect');
const httpProxyMiddleware = require('http-proxy-middleware');
const httpProxy = httpProxyMiddleware.createProxyMiddleware;

function proxy(context: string, options: any) {
    let proxy: any;

    if (typeof options === 'string') {
        options = {target: options};
    }

    proxy = httpProxy(context, options);

    return async function (ctx: any, next: Function) {
        await koaConnect(proxy)(ctx, next);
    };
}

app.use(proxy('/socket', {
    target: config.AGENT_SOCKET_URL,
    changeOrigin: true,
    pathRewrite: {
        '^/socket': ''
    },
    ws: true,
    secure: false
}));

你可能感兴趣的:(前端杂事,proxy,webpack,koa2,websocket)