求助,怎样连接上后,让服务端发起向远端的请求,然后把响应发回来呢
发布于 12 年前 作者 jtyjty99999 4164 次浏览 最后一次编辑是 8 年前

我已经明白

var options = { host: ‘XXX.X.X.XX’, port: 7379, path: ‘/GET/soscount’, method: ‘get’ }; http.get(options, function(res) { console.log("Got response: " + res.statusCode); res.on(‘error’, function(e) { console.log("Got error: " + e.message); }).on(‘data’, function (chunk) { console.log('BODY: ’ + chunk); }) });

也会建立

var http = require(‘http’); http.createServer(function(req,res){ res.writeHead(200,{‘Content-Type’:‘text/html’}) res.write(’<h1>node</h1>’) res.end(’<p>hello</p>’) }).listen(4000); console.log(“httpServer is listening at port 4000”)

我现在想 连接到server后,发起那个get请求,之后把数据返回给这个连接的response 应该怎样写呢?

4 回复

代码没标记啊亲… 没理解错的话, 前一段代码放到后一段代码 createServer 的回调函数里, 然后把 res.write 放到 http.get 的回调函数里(变量名不能重复就是了), 那样就可以了.

谢谢你的回答啊。。 是这个意思么:

var http = require('http');
http.createServer(function (req, resq) {
	var options = {
		host : '111.1.3.68',
		port : 7379,
		path : '/GET/soscount',
		method : 'get'
	};
	http.get(options, function (res) {
		console.log("Got response: " + res.statusCode);
		res.on('error', function (e) {
			console.log("Got error: " + e.message);
		}).on('data', function (chunk) {
			console.log('BODY: ' + chunk);
		}).end(
			resq.writeHead(200, {
				'Content-Type' : 'text/html'
			})
			resq.write('<h1>node</h1>')
			resq.end('<p>hello</p>'))
	});
}).listen(4000);
console.log("httpServer is listening at port 4000")

然后resq他找不到啊。。。

var http = require('http'),
q = require('querystring');

http.createServer(function (req, res) {
    //创建geo 经纬度, 用于取Google 地图
    var url=["/maps/geo?q="
        ,q.parse(req.url)["long"]
        ,","
        ,q.parse(req.url)["lat"]
        ,"&output=json&sensor=false"].join(""),
        //创建options
        options={host:"maps.google.com" ,path:url};

    //log
    console.log("url:",options.host+options.path);
    console.log("requrl:",req.url);

    //服务端发出请求get
    http.get(options,function(response){
        //console.log("hi",response);
        res.writeHead(200, {'Content-Type': 'text/plain'});
        var pageData = "";
        response.setEncoding('utf8');
        //接受数据,保存
        response.on('data', function (chunk) {
          pageData += chunk;
        });

        //数据接收完毕, 输出到客户端
        response.on('end', function(){
          res.write(pageData);
          res.end();
        });

    });

}).listen(80);

看了你的,明白怎么写了,非常感谢你们的回答!

回到顶部