1

/node_modules/http-proxy/lib/http-proxy/index.js:120; 错误:套接字挂起

上一篇:/node_modules/http-proxy/lib/http-proxy/index.js:120; 错误:套接字挂起

我正在尝试使用createProxyMiddleware({ target: serviceProvider})而不是 apiProxy.web(req, res, {target: serviceProvider});. 浏览器挂起并且不显示任何内容(尽管我在选项卡中看到了旋转)

如何正确使用带有嵌套代码库的 createProxyMiddleware,如下所示?

这是源代码。

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);
            }
        }
    },
);

之间,这有效:app.get('/source*', createProxyMiddleware({ target: serviceProvider}))

4

1 回答 1

1

问题是代理中间件已创建但未实际调用,因此请求挂起。解决此问题的一种方法是像您一样创建中间件(但最好在路由处理程序之外,因为它将在每个请求上创建),然后使用当前快速中间件的参数调用它:

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 ... 
    });
于 2020-04-04T17:54:04.193 回答