admin管理员组

文章数量:1389903

I have a node.js / express project and I try to implement http-proxy-middleware like this :

const app = express();
...
// 1st : `/mainUrls/*` are processed by the main app
app.use("/mainUrls", routerMainUrls);
....
// 2nd : `/api/url1` and `/api/url2` are forwarded to another app
const proxyTable: any = { 
    "/api/url1" : "http://localhost:3010",
    "/api/url2" : "http://localhost:3020",
};
const options = {
    router: proxyTable,
};
const myProxy = createProxyMiddleware(options);
app.use(myProxy);
...
// 3rd : All others URLs
app.use(routerAnotherUrls);
....

The proxy is working correctly. If I receive a url like /api/url1 it is forwarded to the right destination. However, if the url does not match the first or second case, I want it to be handled by the 3rd. I have good reasons for anizing my routers this way. How can I tell to http-proxy-middleware to continue if the proxy table is not satisfied ?

I have a node.js / express project and I try to implement http-proxy-middleware like this :

const app = express();
...
// 1st : `/mainUrls/*` are processed by the main app
app.use("/mainUrls", routerMainUrls);
....
// 2nd : `/api/url1` and `/api/url2` are forwarded to another app
const proxyTable: any = { 
    "/api/url1" : "http://localhost:3010",
    "/api/url2" : "http://localhost:3020",
};
const options = {
    router: proxyTable,
};
const myProxy = createProxyMiddleware(options);
app.use(myProxy);
...
// 3rd : All others URLs
app.use(routerAnotherUrls);
....

The proxy is working correctly. If I receive a url like /api/url1 it is forwarded to the right destination. However, if the url does not match the first or second case, I want it to be handled by the 3rd. I have good reasons for anizing my routers this way. How can I tell to http-proxy-middleware to continue if the proxy table is not satisfied ?

Share asked Mar 14 at 14:07 gduhgduh 1,18214 silver badges32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Doesn't seem to be an option to call next middleware from router, so, you might instead create a middleware that will check paths and either call proxy middleware, or another middleware:

const myProxy = createProxyMiddleware(options);

const proxyUrls = Object.keys(proxyTable);

app.use((req, res, next) => {
    if (proxyUrls.includes(req.path)) {
        myProxy(req, res);
    } else {
        routerAnotherUrls(req, res);
    }
});

本文标签: nodejsHow to continue in case of the router is not satisfied using httpproxymiddlewareStack Overflow