No response using express proxy route

后端 未结 5 910
执念已碎
执念已碎 2020-12-07 08:55

I\'ve written a small proxy with nodejs, express and htt-proxy. It works well for serving local files but fails when it comes to proxy to external api:

var e         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 09:52

    Even simpler with pipe and request-Package

    var request = require('request');
    
    app.use('/api', function(req, res) {
      var url = apiUrl + req.url;
      req.pipe(request(url)).pipe(res);
    });
    

    It pipes the whole request to the API and pipes the response back to the requestor. This also handles POST/PUT/DELETE and all other requests \o/

    If you also care about query string you should pipe it as well

    req.pipe(request({ qs:req.query, uri: url })).pipe(res);
    

提交回复
热议问题