美文网首页
umijs proxy 配置

umijs proxy 配置

作者: 想溜了的蜗牛 | 来源:发表于2021-05-13 16:19 被阅读0次

    umijs 中使用代理对新手来说其实有点莫名其妙,感觉就像被蒙眼走路。是否走对完全靠运气。因此有了想对它了解更多的想法,起码能知道请求的链接具体什么。于是查到资料说umi用的其实是 http-proxy-middleware, 然后在它的 issue 中看到 How to log request and response urls, 具体代码:

    var proxyOpts = {
        target: 'https://my-app.herokuapp.com/',
        pathRewrite: {
            '^/v1' : '/api/v1'
        },
        onProxyReq: function onProxyReq(proxyReq, req, res) {
            // Log outbound request to remote target
            const exchange = `[${req.method}] [${proxyRes.statusCode}] ${req.path} -> ${proxyRes.req.protocol}//${proxyRes.req.host}${proxyRes.req.path}`;
            console.log(exchange); // [GET] [200] / -> http://www.example.com
        },
        onError: function onError(err, req, res) {
            console.error(err);
            res.status(500);
            res.json({error: 'Error when connecting to remote server.'});
        },
        logLevel: 'debug',
        changeOrigin: true,
        secure: true
    };
    

    看方法 onProxyReq 即可。

    同时也可以参考下 stockoverlfow 的问题 log-request-responses-bodies-with-http-proxy-middleware

    app.use('/proxy/:service/', proxy({
            pathRewrite: function(path, req){
                ...
            },
            router: function(req) {
                ...
            },
            onProxyRes: function(proxyRes, req, res) {
                log("Req URL: " + req.originalUrl);
                log("Response status code: " + proxyRes.statusCode);
            }
    }));
    

    注意: req.originalUrl

    相关文章

      网友评论

          本文标题:umijs proxy 配置

          本文链接:https://www.haomeiwen.com/subject/aiotjltx.html