在 express JS 服务器中使用 http-proxy

use http-proxy inside a express JS server

我在网上得到了一个基于express nodeJS的登录页面代码。

我在不同的端口上有很多后端应用 运行ning。目标是,当用户在 nodeJS 服务器中通过身份验证时,他会自动重定向到他的应用程序。

但是,如果我可以单独安装一个 http-proxy 并且 运行 它正确,我想在用户连接时在此登录 JS 代码中包含代理。

下面是部分代码

const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer();

(...)

// http://localhost:3000/auth
app.post('/auth', function(request, response) {
    // Capture the input fields
    let username = request.body.username;
    let password = request.body.password;
    // Ensure the input fields exists and are not empty
    if (username && password) {
        // Execute SQL query that'll select the account from the database based on the specified username and password
        connection.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {
            // If there is an issue with the query, output the error
            if (error) throw error;
            // If the account exists
            if (results.length > 0) {
                // Authenticate the user
                request.session.loggedin = true;
                request.session.username = username;
                // Redirect to home page

                proxy.web(req, res, { target: 'http://127.0.0.1:1881' });

                //response.redirect('/home');
            } else {
                response.send('Incorrect Username and/or Password!');
            }           
            response.end();
        });
    } else {
        response.send('Please enter Username and Password!');
        response.end();
    }
});
app.listen(3000);

response.redirect('/home');我想通过代理替换它,但没有附加内容。

我不知道这是否可行,因为运行在同一个实例上连接 2 个服务器。

感谢您的帮助。

关注

我觉得用express的话还是用这个包比较好:https://www.npmjs.com/package/express-http-proxy

你可以这样使用它:

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

const proxyMiddleware = createProxyMiddleware({
  target: 'foo',
  onProxyReq: fixRequestBody,
  logLevel: 'debug',
  changeOrigin: true,
  secure: false,
  xfwd: true,
  ws: true,
  hostRewrite: true,
  cookieDomainRewrite: true,
  headers: {
    "Connection": "keep-alive",
    "Content-Type": "text/xml;charset=UTF-8",
    "Accept": "*/*"
  },
});

app.use( '/youRoute/**', proxyMiddleware );

然后当您登录时,您会重定向到您代理的路由:

res.redirect('/youRoute/');