当前位置:  开发笔记 > 编程语言 > 正文

如何在节点js中转发http请求

如何解决《如何在节点js中转发http请求》经验,为你挑选了1个好方法。

我想接受一个请求,将它转发到另一个url并返回forwared请求的结果.

这是我的代码:

const http = require('http'),
      server = http.createServer().listen(3000);

const baseUrl = 'foo.bar';

server.on('request', (req, res) => {
    req.headers.host = baseUrl;

    var connector = http.request(req, (resp) => {
        resp.pipe(res);
    });

    req.pipe(connector);
});

可悲的是,我收到错误,插座挂断了.

Error: socket hang up
    at createHangUpError (_http_client.js:203:15)
    at Socket.socketOnEnd (_http_client.js:288:23)
    at emitNone (events.js:72:20)
    at Socket.emit (events.js:166:7)
    at endReadableNT (_stream_readable.js:903:12)
    at doNTCallback2 (node.js:439:9)
    at process._tickCallback (node.js:353:17)

有谁知道,我做错了什么?



1> Nazar Sakhar..:

尝试手动配置新请求对象,不要更改req对象.

这有效:

const http = require('http'),
    server = http.createServer().listen(3000);

const baseUrl = 'www.i.ua';

server.on('request', (req, res) => {
  var connector = http.request({
    host: baseUrl,
    path:'/',
    method: 'GET',
    headers: req.headers
  }, (resp) => {
    resp.pipe(res);
  });

  req.pipe(connector);
});

所以,你应该有这样的事情:

const http = require('http'),
    server = http.createServer().listen(3000);

const baseUrl = 'radio.i.ua';

server.on('request', (req, res) => {
  var connector = http.request({
    host: baseUrl,
    path: req.url,
    method: req.method,
    headers: req.headers
  }, (resp) => {
    resp.pipe(res);
  });

  req.pipe(connector);
});

推荐阅读
yzh148448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有