使用 express.js 代理 [英] Proxy with express.js

查看:34
本文介绍了使用 express.js 代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了避免同域 AJAX 问题,我希望我的 node.js Web 服务器将来自 URL /api/BLABLA 的所有请求转发到另一台服务器,例如 other_domain.com:3000/BLABLA,并将此远程服务器返回的相同内容透明地返回给用户.

To avoid same-domain AJAX issues, I want my node.js web server to forward all requests from URL /api/BLABLA to another server, for example other_domain.com:3000/BLABLA, and return to user the same thing that this remote server returned, transparently.

所有其他 URL(除了 /api/*)都将直接提供,没有代理.

All other URLs (beside /api/*) are to be served directly, no proxying.

我如何使用 node.js + express.js 实现这一点?能举个简单的代码例子吗?

How do I achieve this with node.js + express.js? Can you give a simple code example?

(Web 服务器和远程 3000 服务器都在我的控制之下,都运行 node.js 和 express.js)

(both the web server and the remote 3000 server are under my control, both running node.js with express.js)

到目前为止我发现了这个 https://github.com/http-party/node-http-proxy ,但阅读那里的文档并没有让我更明智.我结束了

So far I found this https://github.com/http-party/node-http-proxy , but reading the documentation there didn't make me any wiser. I ended up with

var proxy = new httpProxy.RoutingProxy();
app.all("/api/*", function(req, res) {
    console.log("old request url " + req.url)
    req.url = '/' + req.url.split('/').slice(2).join('/'); // remove the '/api' part
    console.log("new request url " + req.url)
    proxy.proxyRequest(req, res, {
        host: "other_domain.com",
        port: 3000
    });
});

但是没有任何东西返回给原始 Web 服务器(或最终用户),所以没有运气.

but nothing is returned to the original web server (or to the end user), so no luck.

推荐答案

您想使用 http.request 创建一个对远程 API 的类似请求并返回其响应.

You want to use http.request to create a similar request to the remote API and return its response.

像这样:

const http = require('http');
// or use import http from 'http';


/* your app config here */

app.post('/api/BLABLA', (oreq, ores) => {
  const options = {
    // host to forward to
    host: 'www.google.com',
    // port to forward to
    port: 80,
    // path to forward to
    path: '/api/BLABLA',
    // request method
    method: 'POST',
    // headers to send
    headers: oreq.headers,
  };

  const creq = http
    .request(options, pres => {
      // set encoding
      pres.setEncoding('utf8');

      // set http status code based on proxied response
      ores.writeHead(pres.statusCode);

      // wait for data
      pres.on('data', chunk => {
        ores.write(chunk);
      });

      pres.on('close', () => {
        // closed, let's end client request as well
        ores.end();
      });

      pres.on('end', () => {
        // finished, let's finish client request as well
        ores.end();
      });
    })
    .on('error', e => {
      // we got an error
      console.log(e.message);
      try {
        // attempt to set error message and http status
        ores.writeHead(500);
        ores.write(e.message);
      } catch (e) {
        // ignore
      }
      ores.end();
    });

  creq.end();
});

注意:我还没有真正尝试过上面的方法,所以它可能包含解析错误,希望这会给你一个关于如何让它工作的提示.

这篇关于使用 express.js 代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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