How do I use createProxyMiddleware with the nested logic

独自空忆成欢 提交于 2020-05-28 07:07:05

问题


/node_modules/http-proxy/lib/http-proxy/index.js:120; Error: socket hang up

Previous Post: /node_modules/http-proxy/lib/http-proxy/index.js:120; Error: socket hang up

I'm trying to use createProxyMiddleware({ target: serviceProvider}) instead of apiProxy.web(req, res, {target: serviceProvider});. The browser hangs and doesn't show anything (I see the spin in the tab though)

How do I properly use createProxyMiddleware with the nested codebase like below?

Here is the source code.

app.get('/source*',
    function(req, res, next) {
        req.query.RelayState = req.url;
        if(req.user) { // if user is authenticated,
            if(req.originalUrl) {
                resource_path = req.originalUrl.split('/source')[1];
                console.log(req.user['email'] + ' is viewing ' + req.originalUrl);
            }
            createProxyMiddleware({ target: serviceProvider})
            // apiProxy.web(req, res, {target: serviceProvider});
        } else {
            if(process.env.MODE=='HACK') {
              createProxyMiddleware({ target: serviceProvider})
              // apiProxy.web(req, res, {target: serviceProvider});
            } else {
              passport.authenticate('samlStrategy')(req, res, next);
            }
        }
    },
);

Between, this works: app.get('/source*', createProxyMiddleware({ target: serviceProvider}))


回答1:


The problem is that the proxy middleware is created but not actually called and as a result the request hangs. One way to solve this is to create the middleware as you did (but preferably outside the route handler, as it would get created on each request), and then call it with the current express middleware's arguments:

const serviceProviderProxy = createProxyMiddleware({target: serviceProvider }); 

    app.get('/source*', (req, res, next) => {
        req.query.RelayState = req.url;
        if (req.user) { // if user is authenticated,
            if (req.originalUrl) {
                resource_path = req.originalUrl.split('/source')[1];
                console.log(req.user['email'] + ' is viewing ' + req.originalUrl);
            }
            return serviceProviderProxy.call(serviceProviderProxy, req, res, next); // you need to return here if there's more code below the else block, otherwise return is not needed
        } else {
            if(process.env.MODE=='HACK') {
               return serviceProviderProxy.call(serviceProviderProxy, req, res, next);              
            } else {
               passport.authenticate('samlStrategy')(req, res, next);
            }
        }
        // potential more code ... 
    });


来源:https://stackoverflow.com/questions/61021398/how-do-i-use-createproxymiddleware-with-the-nested-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!