使用nodejs的代理

时间:2011-09-25 11:54:18

标签: node.js proxy express

我开发了一个针对api的webapp。由于api没有在我的本地系统上运行,我需要代理请求,所以我不会在跨域问题上运行。有没有一种简单的方法可以做到这一点,所以我的index.html将从本地和所有其他GET,POST,PUT,DELETE请求发送到xyz.net/apiEndPoint。

编辑:

这是我的第一个解决方案,但没有工作

var express = require('express'),
    app = express.createServer(),
    httpProxy = require('http-proxy');


app.use(express.bodyParser());
app.listen(process.env.PORT || 1235);

var proxy = new httpProxy.RoutingProxy();

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/index.html');
});
app.get('/js/*', function(req, res) {
    res.sendfile(__dirname + req.url);
});
app.get('/css/*', function(req, res) {
    res.sendfile(__dirname + req.url);
});

app.all('/*', function(req, res) {
    proxy.proxyRequest(req, res, {
        host: 'http://apiUrl',
        port: 80
    });

});

它将提供索引,js,css文件,但不要将其余的路由到外部api。这是我收到的错误消息:

An error has occurred: {"stack":"Error: ENOTFOUND, Domain name not found\n    at IOWatcher.callback (dns.js:74:15)","message":"ENOTFOUND, Domain name not found","errno":4,"code":"ENOTFOUND"}

4 个答案:

答案 0 :(得分:5)

看看readme for http-proxy。它有一个如何调用proxyRequest的例子:

proxy.proxyRequest(req, res, {
  host: 'localhost',
  port: 9000
});

根据错误消息,听起来好像是在将伪造的域名传递给proxyRequest方法。

答案 1 :(得分:2)

其他答案略显过时。

以下是如何将http-proxy 1.0与express:

一起使用
var httpProxy = require('http-proxy');

var apiProxy = httpProxy.createProxyServer();

app.get("/api/*", function(req, res){ 
  apiProxy.web(req, res, { target: 'http://google.com:80' });
});

答案 2 :(得分:1)

以下是可以修改请求/响应正文的代理示例。

它评估实现透明读/写流的through模块。

var http = require('http');
var through = require('through');

http.createServer(function (clientRequest, clientResponse) {

    var departureProcessor = through(function write(requestData){

        //log or modify requestData here
        console.log("=======REQUEST FROM CLIENT TO SERVER CAPTURED========");
        console.log(requestData);

        this.queue(requestData);
    });

    var proxy = http.request({ hostname: "myServer.com", port: 80, path: clientRequest.url, method: 'GET'}, function (serverResponse) {

        var arrivalProcessor = through(function write(responseData){

            //log or modify responseData here
            console.log("======RESPONSE FROM SERVER TO CLIENT CAPTURED======");
            console.log(responseData);

            this.queue(responseData);
        });

        serverResponse.pipe(arrivalProcessor);
        arrivalProcessor.pipe(clientResponse);
    });

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

}).listen(3333);

答案 3 :(得分:0)

也许你应该看看我的回答here。在这里,我使用请求包将每个请求传递给代理,并将响应传递回请求者。

相关问题