如何在expressjs中更改BaseURL [HOST]

时间:2018-03-07 21:11:02

标签: node.js express

我使用的是以下代码,我正在使用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:5001https://example.com

1 个答案:

答案 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);