javascript - 到不同服务的单端口路由
问题描述
我的问题是:http-proxy、reverse-proxy.js或任何其他库(除了像 nginx 这样的网络服务器)是否能够根据 url 将来自端口 80 的所有请求路由到另一个服务?
如果带有该 url 的请求来自端口 80,localhost:80/route1
我想将其重定向到服务localhost:3001
如果带有该 url 的请求来自端口 80,localhost:80/another-route
我想将其重定向到localhost:3002
. 等等..
总结一下:我想公开 1 个端口(80),然后根据请求中的 URL 模式将请求路由到其他服务。到目前为止,我在下面使用reverse-proxy.js尝试了这种方法,但它仅在端口更改时才有效
{
"port": 80,
"routes": {
"localhost/test": "localhost:3001",
"localhost/another-route": "localhost:3002",
"localhost/another-route-same-service": "localhost:3002",
"*": 80
}
}
解决方案
是的,当然可以。这是一个非常普遍的要求。在 Node 中,您可以使用流在本地完成它。这是一个仅使用标准 Node http库的完整工作示例。
const http = require('http');
const server = http.createServer();
let routes = {
'/test': {
hostname: 'portquiz.net',
port: 80
}
}
function proxy(req, res){
if (!routes[req.url]){
res.statusCode = 404;
res.end();
return;
}
let options = {
...routes[req.url],
path: '', // if you want to maintain the path use req.url
method: req.method,
headers: req.headers
}
let proxy = http.request(options, function(r){
res.writeHead(r.statusCode, r.headers);
r.pipe(res, { end: true });
})
req.pipe(proxy, { end: true }).on('error', err => console.log(err))
}
server.on('request', proxy);
server.listen(8080);
推荐阅读
- ruby-on-rails - 如何修改 Rails 中的嵌套参数?
- javascript - 如何使用 ajax 在 Laravel 中保存播放 currentTime 的视频
- python - 如何将图片转换为像 Dataarray 这样的 MNIST
- python - 在 python 虚拟环境中安装烧瓶的问题
- linux - 多用户情况下 apache2 的性能优化
- java - 如何修复错误 403 以便我可以推送
- kubernetes - 如何在 oc 3.1 中将身份提供者更改为 htpasswd
- python - Matplotlib 错误:“x 和 y 必须具有相同的第一维,但具有形状 (100,) 和 (1,)”
- php - 如何消除?在这个带有 preg_mach 的字符串中
- python - 通过引用字符串位置检查数据框列中的子字符串