转发快递js路由到其他服务器 [英] Forward express js route to other server

查看:84
本文介绍了转发快递js路由到其他服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个express.js应用程序,并希望从其他服务器提供某些路由。

I'm writing an express.js app and would like to serve certain routes from another server.

Express提供从开始的一些路由api.example.com/v1 / * 。我希望任何以 / ad / hoc / 开头的路径转发到另一台服务器并由Express提供响应,例如 api.example.com/ad/hoc/endpoint.php 将通过管道传输到 grampas-lamp-stack.example.com/ad/hoc/ endpoint.php

Express serves some routes starting with api.example.com/v1/*. I would like any paths starting with /ad/hoc/ to be forwarded to another server and the response served by Express, e.g. api.example.com/ad/hoc/endpoint.php would be piped to grampas-lamp-stack.example.com/ad/hoc/endpoint.php.

我可以用 res.redirect 完成此操作,但我d喜欢通过我的Express应用程序流式传输响应,并避免将浏览器重定向到另一个IP地址。

I can accomplish this with res.redirect but I'd like to stream the response through my Express app and avoid redirecting the browser to another IP address.

app.js

var express = require('express');
var app = express();

app.get('/v1/users/:id', UserCtrl.get);
app.get('/v1/users/search', UserCtrl.search);

app.get('/ad/hoc/*', function(req, res) {
  res.redirect('http://grampas-lamp-stack.example.com' + req.url);
}

我尝试搜索代理请求快递但我不确定 proxy 是否是我正在做的事情的准确术语。如果这个话题有更好的词或我想要完成的事情,请告诉我。

I tried searching "proxy requests express" but I'm not sure if proxy is an accurate term for what I'm doing. If there's a better word for this topic or what I'm trying to accomplish, please let me know.

推荐答案

您可以使用 express-http-proxy

是的,代理是您正在寻找的准确术语。它将在下面将请求转发到另一个URL,因为API也意味着。

And yes, proxying is the accurate term for what you are looking for. It will underneath forward the request to another url, as the API will also imply.

以下是一个示例用法:

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

app.use('/route/you/want/proxied', proxy('proxyHostHere', {
    forwardPath: function (req, res) {
      return '/path/where/you/want/to/proxy/' + req.url
    }
}))

这篇关于转发快递js路由到其他服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆