Замена nginx в качестве обратного прокси с помощью express - PullRequest
0 голосов
/ 02 июня 2018

Я хотел бы заменить nginx , выступающий в качестве обратного прокси, на узел js express , чтобы я мог настроить правила динамически ииметь лучшие возможности ведения журналов и тестирования.

Моя настройка nginx выглядит следующим образом:

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        off;
    keepalive_timeout  65;
    gzip  on;

    server {
        listen       8023;
        server_name  localhost;
        sendfile        off;

        location / {
            proxy_pass https://main.app.url.com/;
        }

        location /module1/v1/ {
            client_max_body_size 30000M;
            client_body_buffer_size 200000k;
            # local backend of module 1
            proxy_pass http://localhost:8080/module1/v1/;
        }

        location /module1/v1/web/ {
            # local front end files for module 1
            alias /some/local/path/build/dist;
        }

        location /module2/v1/web/ {
            # local front end files for module 1
            alias /some/other/local/path/build/dist;
        }
    }
}

Я пытался использовать промежуточное ПО express-http-proxy, но я борюсь с применением вышеприведенногоправила к нему.Во-первых, я не до конца понимаю разницу между директивами proxy_pass и alias .

Во-вторых, я попробовал следующее:

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

const path = '/some/local/path/build/dist';

app.all('/module1/v1/web/', proxy(path, {
            proxyReqPathResolver: (req) => {
                return '';
            }
        })
    );
};

Я получилошибка:

TypeError: Cannot read property 'request' of undefined
    at /Users/user1/Dev/local-dev-runner/node_modules/express-http-proxy/app/steps/sendProxyRequest.js:13:29
    at new Promise (<anonymous>)
    at sendProxyRequest (/Users/user1/Dev/local-dev-runner/node_modules/express-http-proxy/app/steps/sendProxyRequest.js:11:10)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

Хотя cont path = 'http://www.google.com' вернул правильный ответ.

1 Ответ

0 голосов
/ 07 сентября 2018

Итак, вот с чем я пришел:

Хитрость в том, чтобы обслуживать локальные файлы и веб-запросы прокси .Очевидно, nginx может автоматически распознавать, является ли URI запросов локальным или удаленным путем.

Я решил использовать пакеты nmp is-url и express-http-прокси так, рабочий раствор выглядит так:

const express   = require('express');
const app       = express();
const isUrl     = require('is-url');
const proxy     = require('express-http-proxy');

...

/**
 * Function adding new redirects to the current server instance. If the target URL is an URL the request will be
 * handeled with the express-http-proxy middleware. If the target URL is some local directory the content will be serverd using the express-static middleware.
 * @param matchedPath The path (endpoint) for which the redireciton should be configured.
 * @param targetUrl The target URL or directory for the redirection.
 */
const setUpRedirect = (matchedPath, targetUrl, name) => {
    // Use proxy for Urls 
    if (isUrl(targetUrl)) {
        app.use(matchedPath,
            proxy(targetUrl,
                {
                    memoizeHost: false,
                    limit: '50mb',
                    proxyReqPathResolver: function(req) {
                        // I do not have (yet) any clue why I had to do this but it fixed the behavior
                        return req.originalUrl;
                    },
                }),
        )
    }
    else { // When targetUrl is directory serve static files from there
        app.use(matchedPath,
            express.static(targetUrl),
        );
    };  
};

...

setUpRedirect('/module1/v1/web/:major([0-9]+).:minor([0-9]+).:bugfix([0-9]+)', '/some/local/path/build/dist';)
setUpRedirect('/module2/v1/web/:major([0-9]+).:minor([0-9]+).:bugfix([0-9]+)', 'http://some/remote/url/';)
server = app.listen(8080);
...