我是 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
发送到原始客户端响应
?
顺便说一句,网址可能是 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)
最佳答案
将 var http = require('http');
更改为 var http = require('https');
关于node.js - Nodejs 中的处理程序响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22061121/