用Express.js写一个API透明代理服务器

需要安装的npm包不列了,自行从require里安装吧。

var express = require('express');
var request = require('request');

var remoteUrl = "http://api.xxx.com";
var serverPort = "80";

app = express();
app.listen(serverPort);

// Default : proxy to remoteUrl
app.use('*', function(req, res){
    var url = remoteUrl + req.originalUrl;
    console.log("Proxy: " + url);
    // POST or GET
    var r = null;
    if(req.method === 'POST') {
        r = request.post({uri: url, json: req.body});
    } else {
        r = request(url);
    }
    // do real proxy
    req.pipe(r).pipe(res);
});

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *