问题
/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