我使用的是以下代码,我正在使用express-http-proxy:
const express = require('express');
const proxy = require('express-http-proxy');
var baseUrl2 = "https://localhost:5002";
var app = express();
app.use('/api', proxy(baseUrl2, {
// I want to change the baseUrl2 before making the request.
proxyReqPathResolver: (req) => {
const modifiedURL = "/someChanges"
return require('url').parse(modifiedURL).path;
},
}));
app.listen(3000);
我可以将网址从https://localhost:5002
更改为https://localhost:5002/someChange
。
但我需要将其从https://localhost:5002
更改为https://localhost:5001
或https://example.com
。
答案 0 :(得分:1)
我可以使用proxyReqOptDecorator
选项更改端口。我正在使用proxyReqOpts.port
更改端口,但我们也可以使用proxyReqOpts.host
更新代码:
const express = require('express');
const proxy = require('express-http-proxy');
var baseUrl2 = "https://localhost:5002";
var app = express();
app.use('/api', proxy(baseUrl2, {
// I want to change the baseUrl2 before making the request.
proxyReqPathResolver: (req) => {
const modifiedURL = "/someChanges"
return require('url').parse(modifiedURL).path;
},
proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
if(someCondition)
proxyReqOpts.port = 5001;
else
proxyReqOpts.port = 5002;
return proxyReqOpts;
}
}));
app.listen(3000);