代理与nodejs

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

编辑:

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

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"} 

看看http-proxy的自述文件 。 它有一个如何调用proxyRequest

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

根据错误消息,这听起来像是你传递一个假的域名到proxyRequest方法。

其他答案略有过时。

以下是如何使用http-proxy 1.0与快速:

 var httpProxy = require('http-proxy'); var apiProxy = httProxy.createProxyServer(); app.get("/api/*", function(req, res){ apiProxy.web(req, res, { target: 'http://google.com:80' }); }); 

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

through实现透明读/写stream的模块进行评估。

 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); 

也许你应该看看我的答案。 在这里,我使用请求包来pipe理每个请求到代理服务器,并将响应传递给请求者。