下面代码实现的功能是这样的:
首先创建一个HTTP服务器,当服务器接收到客户端的请求后,向"www.taobao.com"网站请求数据,当从该网站接受到的响应数据后,将响应数据发送给客户端.
1 var http=require("http");
2 var url=require("url");
3 var server=http.createServer(function(sreq,sres){
4 var url_parts=url.parse(sreq.url);
5 var opts={
6 host:"www.taobao.cn",
7 port:80,
8 path:url_parts.pathname,
9 headers:sreq.headers
10 };
11 var creq=http.get(opts, function (cres) {
12 sres.writeHead(cres.statusCode,cres.headers);
13 cres.pipe(sres);
14 });
15 sreq.pipe(creq);
16 });
17 server.listen(1337,"127.0.0.1", function () {
18 console.log("开始监听" server.address().port "......");
19 });
运行代码后,在浏览器端运行程序:
发现没有,界面是淘宝的官网,但是地址确实变成我们本地的了.