Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deal with HTTP request in Node

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how to deal with HTTP requests in Node. I think it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.

First, use express generator to quickly build an express project, and command:

Express analysis_http

Follow the prompts to enter the project to install dependencies, and then use npm start to start the express project. So how exactly did our project create a http server and start it? After the express is created, the www file will be generated in the bin folder with the necessary startup configuration. We can look at the www file:

We can initially see that the two main methods, http.createServer () and server.listen (), are called. We may now have a series of questions:

Where do the req and res parameters used by the interface come from? How does createServer () create a server? What exactly does listen () do?

Next, we analyze these problems in detail through the source code. First, pull a copy of the NodeJS source code from gitHub, address:

Https://github.com/nodejs/node.git

Let's first look at the key code of the lib/http.js file:

We can see that the createServer () method returns an instance of Server. And the parameter requestListener is the callback function passed in our API:

Function (req, res, next) {res.send ('respond with a resource');}

You can see the _ http_server.js referenced by Server at the top of the file. So let's take a look at the constructor Server in _ http_server.js:

Because Server inherits net.Server, and net.Server inherits from events.EventEmitter, you can use methods such as on. We can see the callback function with the request and connection events set in the Server constructor:

Request uses the callback method requestListener set in createServer. Connection uses the callback method: connectionListener.

So when will we trigger the connection event? Let's take a look at the key source code of connectionListener:

The ones that need to be noticed here are the parser object and parseOnIncoming (). Let's first look at the parser object, where parser comes from parsers.alloc ():

Const parser = parsers.alloc ()

You can see from the top of the file that parsers comes from the _ http_common.js file. We can look at the source code:

We can see that in order to increase the reuse of parser as much as possible and reduce the consumption of constantly calling constructors, parser adopts the data structure of FreeList, and the upper limit of 1000 parser in the FreeList pool is based on events and uses the http- parser library. Then you can see two more important methods: parseOnHeadersComplete and parserOnMessageComplete.

ParseOnHeadersComplete: this method is triggered when the request header parsing is completed. ParserOnMessageComplete: this method is triggered after the receiving body is completed, and the end event is triggered when the data is received.

Let's take a look at the source code of FreeList:

Http creates 1000 http_parser instances by default, and each time there is a http request, a http_parser is removed from the array and assigned to the current socket. If all 1000 http_parser are allocated, a new http_parser will be assigned. After we parse the request header, the parseOnHeadersComplete method is triggered, and if it is not a request of type udp, the request event is triggered.

After talking about the parser object, let's go back to the parseOnInComing () method we just mentioned. The parseOnInComing () method uses bind and passes in the parameter parser,socket,state.

Parser.onIncoming = parserOnIncoming.bind (undefined, server, socket, state)

Let's first look at the source code of parseOnInComing ():

There is an important judgment as sockket._httpMessage. If the result is true, there are other requests occupying the socket. The parserOnInComing () method is used to process the parsed request, so here it means that the parsing request header and request body have been completed. As I just said, the parserOnHeadersComplete () method will be executed after the request header parsing. Let's look at the source code of the parserOnHeadersComplete () method:

We can see that the call to parser.incoming,parser.incoming is an instance of ParserInComingMessage (socket). ParserInComingMessage inherits from Stream.Readable. Stream is another particularly important knowledge point for NodeJS, but this article will not explain it in depth.

Object.setPrototypeOf (IncomingMessage.prototype, Stream.Readable.prototype); Object.setPrototypeOf (IncomingMessage, Stream.Readable)

So the overall logic should be:

1. Parsing the request header triggers the request event. two。 The parserOnHeadersComplete () method is executed when the request header is parsed. 3. The parseOnIncoming () method is executed in the parserOnHeadersComplete () method. 4. Finally, server.emit ('request', req, res).

When the request event is triggered, pass in the parameters req and res. Because we said at the beginning that request binds the callback method:

Function (req, res, next) {res.end ('respond with a resource');}

So the callback method is executed when the request is triggered. However, the body data is not parsed, and the body data is stored in the stream until the user triggers the data event to receive the data in the body. The res.end () event is triggered in the callback method. So what exactly did listen () do?

Because the listen () event is triggered only if the connection event is triggered. So first take a look at the onconnection () source code:

Let's go on to look at the source code that calls the onconnection () method:

SetupListenHandle (address, port, addressType, backlog, fd)

You can see that _ listen2 is used at the bottom. Let's move on to the source code for the call _ listen2:

You can see that server._listen2 is called internally. Let's look at the source code for the call to listenInCluster again:

We use recursive methods that are called from the bottom up, so the overall process should be:

1.listen () calls listenInCluster (this, pipeName,-1,-1, backlog, undefined, options.exclusive); 2. Call server._listen2 (address, port, addressType, backlog, fd, flags) in listenInCluste (); 3. Then call setupListenHandle (address, port, addressType, backlog, fd, flags); 4. Onconnection () is called in setupListenHandle (). 5. Finally go back to the listen () method and self.emit ('connection', socket); this is how to handle HTTP requests in Node. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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: 220

*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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report