How to redirect incoming URL requests by adding additional parameters

后端 未结 3 522
慢半拍i
慢半拍i 2021-01-14 18:56

Problem: I get an incoming HTTP request to my server application. The request is something like this : http://example.com?id=abc. I need to parse this request, patch additio

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-14 19:36

    This is a classical error when coming to the async world. You don't return the value of the file, you pass a callback as a parameter and execute it with the end value like so:

    function proxyUrl(id, cb) {
      http.request(options, function(res) {
        // do stuff
        res.on('data', function (chunk) {
          temp = temp.concat(chunk);
        });
        res.on('end', function(){
          // instead of return you are using a callback function
          cb(temp);
        });
    }
    
    function onRequest(req, res) {
      // do stuff
      proxyUrl(id, function(htmlContent) {
        // you can write the htmlContent using req.end here
      });
    }
    
    http.createServer(onRequest).listen(8888);
    

提交回复
热议问题