使用nodejs的代理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用nodejs的代理相关的知识,希望对你有一定的参考价值。

我开发了一个针对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
    at IOWatcher.callback (dns.js:74:15)","message":"ENOTFOUND, Domain name not found","errno":4,"code":"ENOTFOUND"}
答案

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

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

基于错误消息,听起来你正在将伪造的域名传递给proxyRequest方法。

另一答案

其他答案略显过时。

以下是如何使用http-proxy 1.0 with 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' });
});
另一答案

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

它评估实现透明读/写流的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);
另一答案

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

以上是关于使用nodejs的代理的主要内容,如果未能解决你的问题,请参考以下文章

javascript 用于在节点#nodejs #javascript内设置react app的代码片段

nodejs之mock与跨域代理的三两事

scrapy按顺序启动多个爬虫代码片段(python3)

NodeJs GraphQL 片段解析器

如何使用 NodeJs 代理多个文件上传?

nodejs简易代理服务器