nodejs中的处理程序响应

时间:2014-02-27 06:52:23

标签: node.js

我是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

顺便说一句,网址可能是httphttps


更新

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)

2 个答案:

答案 0 :(得分:5)

public static void Main() { var input = @"**Albert School**: George Branson, Eric Towson, Nancy Vanderburg; **Hallowed Halls**: Ann Crabtree, Jane Goodall, Rick Grey, Tammy Hudson; **XXX University**: Rick Anderson, Martha Zander;"; var universities = input .Split(';') .Select(ParseUniversity) .ToArray(); } public static University ParseUniversity(string line) { var fields = line .Split(',',':') .Select(f=>f.Trim('*','\n','\r', '\t' ,' ')) // remove trailing crap .ToArray(); var universityName = fields.First(); var persons = fields .Skip(1) // skip university field .Select(ParsePerson) .ToArray(); return new University {Name = universityName, Persons = persons}; } public static Person ParsePerson(string field) { var p = field.Split(' '); return new Person{FirstName = p.First(), LastName = p.Last()}; } public class University { public string Name {get;set;} public Person[] Persons {get;set;} } public class Person { public string FirstName {get;set;} public string LastName {get;set;} } 更改为var http = require('http');

答案 1 :(得分:1)

我不完全理解你的例子。对我来说很奇怪。但最好将请求响应传递到服务器响应中:

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