简体   繁体   中英

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. 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 ? 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). 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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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