It has been in contact with Node.js for many years and has always enjoyed its single-threaded model and asynchronous IO features, as well as the flexibility of the JavaScript language itself. At the same time, JavaScript has a unique advantage in the whole stack development field. Take a look today at how easy it is to accomplish a simple proxy server function as a service-side language JavaScript.
Simply put, a proxy server is the intermediary server that the proxy user accesses to the target site. As a front-end developer, the common use of agents is cross-domain access to the background APIs. Of course, it can also be used for scientific Internet. The code to share today is related to scientific Internet.
Say not much, first on the code:
var express = require (' Express ');
var request = require (' request ');
var app = Express ();
App.use ('/', function (req, res) {
var url = ' https://www.baidu.com/' + req.url;
Req.pipe (Request (URL)). pipe (res);
Less than 10 lines of code, the implementation of a simple proxy server functionality. Isn't it amazing?
It should be easy to understand these lines of code if you are familiar with Node.js. The Express module is loaded first, which is a popular framework for creating HTTP servers. Then the request, which encapsulates the various methods of the HTTP request, makes it very easy to initiate the request. Next, instantiate a Express object and set the access route. Finally listen for Port 3000.
First look at the effect. Save the above code to file proxy.jsand execute on the path where the file is located:
node proxy.js
Open Http://localhost:3000/in Browser
The key code is within the routing processing method.
req.pipe(request(url)).pipe(res);
The pipe method is magical, just like its name (pipeline), which passes the browser's request data to the requesting client and then returns the target server's response data back to the browser. This code is too TM concise!
So, how to achieve scientific Internet? Yes, put the code on a server that doesn't have a network lockdown, OK. For example, this www.rendoso.com search is behind the Google agent.
Welcome to Pat (DA) Bricks (shang).
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, if there are questions you can message exchange, but also hope that a lot of support cloud Habitat community!