Search code examples
node.jsexpresshttp-proxy-middleware

Proxy does not work on express. Seems it's not defined


I'm trying to config multiple apps on a single server using the following tutorial on Node.js:

https://itnext.io/hosting-multiple-apps-on-the-same-server-implement-a-reverse-proxy-with-node-a4e213497345

Then in the following code, proxy is seems to be not defined: "TypeError: proxy is not a function" but proxy should be defined on express, am I right? It's even on express reference

const express = require('express');
const proxy = require('http-proxy-middleware');

const {routes} = require('./config.json');

const app = express();

for(route of routes){
    app.use(
        route.route,proxy({
            target: route.address,
            pathRewrite: (path, req) => {
                return path.split('/').slice(2).join('/');
            }
        })
    );
}
app.listen(1000,()=>{
    console.log('Proxy listening on port 1000');
});

Solution

  • Please check the version of http-proxy-middleware. For v0.x, you should use it like this:

    var proxy = require('http-proxy-middleware');
    

    see v0.x readme

    For v1.x.x, you should use it like this:

    const { createProxyMiddleware } = require('http-proxy-middleware');
    

    See v1.x.x readme