在expressJS服务器中使用http代理



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

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

但是,如果我可以安装一个分离的http代理并正确运行它,我希望在连接用户时在这个logginJS代码中包含代理。

下面是代码的一部分。

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/');

最新更新