[英]Proxy with 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\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 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);
也許你應該在這里看看我的答案。 在這里,我使用請求包將每個請求傳遞給代理,並將響應傳遞回請求者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.