Home >Web Front-end >JS Tutorial >Teach you how to use node.js to make a proxy server
This chapter introduces how to use node.js to create a proxy server. It is very detailed with pictures and texts. The code is very concise and easy to understand. I recommend it to everyone.
The function implemented by the following code is as follows:
First create an HTTP server. When the server receives the client's request, it requests data from the "www.taobao.com" website. After receiving the response data, the website sends the response data to the client.
var http=require("http"); var url=require("url"); var server=http.createServer(function(sreq,sres){ var url_parts=url.parse(sreq.url); var opts={ host:"www.taobao.cn", port:80, path:url_parts.pathname, headers:sreq.headers }; var creq=http.get(opts, function (cres) { sres.writeHead(cres.statusCode,cres.headers); cres.pipe(sres); }); sreq.pipe(creq); }); server.listen(1337,"127.0.0.1", function () { console.log("开始监听"+server.address().port+"......"); });
After running the code, run the program on the browser:
No, the interface is Taobao’s official website, but the address does become ours It's local.
Isn’t it fun? In fact, node.js can do a lot of things. Friends, you can develop it yourself.
The above is the entire content of this chapter. For more related tutorials, please visit Node.js Video Tutorial!