我是NodeJS的新手,并且正在工作一个示例:
function test(req,res){
var path = urls[Math.floor(Math.random()*urls.length)];
console.log("try to redirect to:"+path);
http.get(path,function(res_server){
//how to send the data from res_server to res
});
}
并且urls
是网址数组。
我想知道如何将数据从发送res_server
到原始客户端response
?
顺便说一句,网址可能是http
或https
。
更新
var urls=["url1","url2","url3"];
var path = urls[Math.floor(Math.random()*urls.length)]; // find an random item from the array
更新:2
很好,这是完整的简单测试脚本:
var http=require("http");
http.createServer(function(req, res1) {
var url = 'http://www.google.com.hk/images/srpr/logo11w.png';
var hp=require("http");
hp.get(url, function(res2) {
res2.pipe(res1);
});
}).listen(3000);
它有效,但是如果您更改http://www.google.com.hk/...logo..png
为https:/www.google.....png
它将引发错误:
http.js:1840
throw new Error('Protocol:' + options.protocol + ' not supported.');
^
Error: Protocol:https: not supported.
at Object.exports.request (http.js:1840:11)
at Object.exports.get (http.js:1847:21)
at Server.<anonymous> (C:\Users\maven\Desktop\t.js:6:6)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at Socket.socket.ondata (http.js:1966:22)
at TCP.onread (net.js:525:27)
我不完全理解您的榜样。对我来说看起来很奇怪。但是最好是将请求响应通过管道传递到服务器响应中:
http.createServer(function(req, res1) {
var path = url.format({
protocol: 'http:',
host: 'www.google.com'
});
http.get(path, function(res2) {
res2.pipe(res1);
});
}).listen(3000);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句