简体   繁体   English

Node.js中的HTTP代理

[英]http proxy in Node.js

I m trying to create a http proxy in node.js which gets the request and makes a new request to the server. 我试图在node.js中创建一个http代理,该代理获取请求并向服务器发出新请求。 My purpose is getting rid of cross origin problem for a while and test my application. 我的目的是暂时消除跨源问题并测试我的应用程序。 But im getting exception : 但是我越来越异常:

     _stream_readable.js:536
    var ret = dest.write(chunk);
    dest.write is not a function

I m totally newbie in the node.js, so am i on the right path ? 我完全是node.js的新手,所以我走对了吗? or is there a better way to do it ? 还是有更好的方法呢?

app.get('/tlq', (req, res) => {
  console.log('serve: ' + req.url);
  var options = {
    hostname: 'www.google.com',
    port: 80,
    path: req.url,
    method: 'GET'
  };
  var proxy = http.request(options, function (res) {
    res.pipe(res, {
      end: true
    });
  });

  req.pipe(proxy, {
    end: true
  });
});

To get rid of cross origin error, you have to send Access-Control header (before any data is shipped to client). 为了摆脱跨源错误,您必须发送Access-Control标头(在将任何数据发送到客户端之前)。 For this purpose you could use next middleware: 为此,您可以使用下一个中间件:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM