In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to implement the nodejs proxy server manually". In the daily operation, I believe that many people have doubts about how to implement the nodejs proxy server manually. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to implement the nodejs proxy server manually". Next, please follow the editor to study!
Recently, I have seen such a topic. According to the principle of reverse proxy server, a proxy server is implemented with nodejs, which requires:
1. Third-party packages are not allowed.
2. Be able to proxy get requests.
3. Be able to proxy post requests.
When I first saw this topic, I thought it was nothing, because I had published an article: building a proxy server with nodejs, but after reading the requirements carefully, I found that it was a little different. The previous article used two third-party packages, express and http-proxy-middleware. However, this topic requires that third-party modules cannot be used.
Therefore, this article uses the nodejs native module to implement a proxy server. First of all, let's understand the principle of the proxy server and learn about the proxy server through the following figure:
As we can see from the figure, the role of the proxy server is to relay, receive client requests and send requests to the proxied server.
Let's infer the implementation of the proxy server from the principle of the proxy server:
1. First, we should build a http server. Here we use the createServer method of nodejs's http module.
2. if you receive the request sent by the client, what is the request sent by the client? A popular point is the request message, which is disassembled, including the request line, the request header, and the request body.
3. Send the request message to the target server, where you need to use the request method of the http module.
The code is as follows: the first step is to build a http server, and the code is as follows:
Const http = require ("http"); const server = http.createServer ()
Server.on ('request', (req,res) = > {res.end ("hello world")})
Server.listen (3000, () = > {console.log ("running");})
Very simple code, without much explanation, and then implement the second step, receiving the request message sent by the client to the proxy server, and testing it to print it out:
Const http = require ("http"); const server = http.createServer (); server.on ('request', (req,res) = > {/ / receive data sent by the client through req's data event and end event / / and process let postbody = [] with Buffer.concat; req.on ("data", chunk = > {postbody.push (chunk)) }) req.on ('end', () = > {let postbodyBuffer = Buffer.concat (postbody); res.end (postbodyBuffer)})}) server.listen (3000, () = > {console.log ("running");})
If you run the above code, you can receive the data sent by the client and return it to the client. You can test it. Here, the main data needs to be processed by buffer in nodejs when transmitting from client to server.
The process is to cram all the received data fragments chunk into an array and then merge them together to restore the source data. Buffer.concat is used in the merge method, and the plus sign cannot be used here. The plus sign implicitly converts the buffer to a string, which is not safe.
Then, in the third step, we use the request method of the http module to forward the request message to the target server. In this step, we need to construct the request message. In the last step, we have already got the data uploaded by the client and lack the request header, so we need to construct our request header according to the request sent by the client, and then send it. The code is as follows:
Const http = require ("http"); const server = http.createServer (); server.on ('request', (req,res) = > {/ / filter request header using es6's extended operator, and propose host connection var {connection, host,... originHeaders} = req.headers / / construct request message var options = {"method": req.method, "hostname": "127.0.0.1", "port": "80", "path": req.url "headers": {originHeaders}} / / receive the data sent by the client through the data event and end event of req / / and process let postbody = [] with Buffer.concat Req.on ("data", chunk = > {postbody.push (chunk);}) req.on ('end', () = > {let postbodyBuffer = Buffer.concat (postbody)) / / define variable to receive the data returned by the target server let responsebody= [] / / send request header var request = http.request (options, (response) = > {response.on ('data', (chunk) = > {responsebody.push (chunk)}) response.on ("end") () = > {/ / process the target server data and return it to the client responsebodyBuffer = Buffer.concat (responsebody) res.end (responsebodyBuffer) }) / / send the received client request data to the target server; request.write (postbodyBuffer) request.end ();}) server.listen (3000, () = > {console.log ("running");})
This is the native proxy server implemented with the http module, where we use the extension operator and deconstruction of es6 to filter the request headers, and use the request method of the http module.
The request method of the http module needs to be passed two parameters when used, and this method returns a request object.
The first parameter of this method is the request header information or, more strictly, the request line and request header information, and the second parameter is the callback function, which gets the content returned by the target server, and uses the processing of data event, end event and buffer when getting the content, but so far, we have not set the request body. A complete request message should contain the request line, the request header and the request body, so how does the request body be sent? the request body is transmitted by calling the write method of the 36-line request object.
Then call the end method on line 37 to send the request.
But looking at so many callbacks nesting, it is really unbearable. We simply optimize it with promise. The code is as follows:
Const http = require ("http"); const server = http.createServer ()
Server.on ("request", (req, res) = > {var {connection, host,... originHeaders} = req.headers Var options = {"method": req.method, / / find a website to test with the table Modified by the proxy website here "hostname": "www.nanjingmb.com", "port": "80", "path": req.url, "headers": {originHeaders}} / / receive the data sent by the client var p = new Promise ((resolve,reject) = > {let postbody = [] Req.on ("data", chunk = > {postbody.push (chunk);}) req.on ('end', () = > {let postbodyBuffer = Buffer.concat (postbody); resolve (postbodyBuffer)})}) / / forward the data and receive the data returned by the target server Then forward it to the client p.then ((postbodyBuffer) = > {let responsebody= [] var request = http.request (options, (response) = > {response.on ('data', (chunk) = > {responsebody.push (chunk)}) response.on ("end") () = > {responsebodyBuffer = Buffer.concat (responsebody) res.end (responsebodyBuffer) })) request.write (postbodyBuffer) request.end ();})}); server.listen (3000, () = > {console.log ("runnng");})
Read the source code carefully. The first promise instance mainly deals with receiving the data sent by the client. Then in the then method, we forward the data obtained in the previous step, receive the data returned by the target server, and then forward it to the client.
At this point, the study on "how to implement the nodejs proxy server manually" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 242
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.