chimurai / http-proxy-middleware

:zap: The one-liner node.js http-proxy middleware for connect, express, next.js and more
MIT License
10.68k stars 826 forks source link

how to dynamic setting target value by request params #879

Closed xpbsm closed 1 year ago

xpbsm commented 1 year ago

Checks

Describe the bug (be clear and concise)

app.use( "/", function (req, res, next) { console.log("middle ware"); next(); }, function (req, res, next) {

const ip = req.ip;

createProxyMiddleware({
  target: ip + '8080',
  changeOrigin: true,
});

next();

}

Step-by-step reproduction instructions

1. package.json {
  "name": "nodegray",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "http-proxy-middleware": "^2.0.6",
    "nodemon": "^2.0.20"
  }
}

2. const express = require("express");
const app = express();
const { createProxyMiddleware } = require("http-proxy-middleware");

app.use(
  "/",
  function (req, res, next) {
    console.log("middle ware");
    next();
  },
  function (req, res, next) {

    const ip = req.ip;

    createProxyMiddleware({
      target: ip + '8080',
      changeOrigin: true,
    });

    next();
  }
);

app.listen(3000);

Expected behavior (be clear and concise)

can proxy dynamic target

How is http-proxy-middleware used in your project?

const express = require("express");
const app = express();
const { createProxyMiddleware } = require("http-proxy-middleware");

app.use(
  "/",
  function (req, res, next) {
    console.log("middle ware");
    next();
  },
  function (req, res, next) {

    const ip = req.ip;

    createProxyMiddleware({
      target: ip + '8080',
      changeOrigin: true,
    });

    next();
  }
);

app.listen(3000);

What http-proxy-middleware configuration are you using?

package.json {
  "name": "nodegray",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "http-proxy-middleware": "^2.0.6",
    "nodemon": "^2.0.20"
  }
}

What OS/version and node/version are you seeing the problem?

Node v16.18.1 Mac V13.0.1

Additional context (optional)

No response

xpbsm commented 1 year ago

// Asynchronous router function which returns promise router: async function(req) { const url = await doSomeIO(); return url; }

I found a way to solve my problem, please close this issue.