Detailed explanation of Node.js http module: request object

foreword

The previous article introduced httpthe basic usage of the module, mainly calling createServerand listenmethods to create and start services. To handle specific HTTP requests, createServerwrite something in the method. This article introduces one of the two core objects that handle requests request.

URL

The HTTP protocol was first designed just to get an HTML document on the network. With the subsequent development, the resources on the network have become more and more abundant, and the types have also developed from a single text to multimedia types such as pictures, audio, and video. But no matter what kind of resource it is, it has a unique identifier in the entire Internet world, which is URL—Uniform Resource Locator (Uniform Resource Locator) .

Here's what the URL consists of:

img

  1. scheme : It is what we often call "protocol", which is translated as "scheme" in "HTTP Definitive Guide". Commonly used protocols are HTTP, FTP, SMTP and so on.
  2. user:password@: Indicates the user and password to access this resource. Authentication is not required for public web resources. Even if it is necessary, it will not be used in this way, it is very unsafe. Usually omitted directly.
  3. host:port: Indicates the host name and port number where the resource is located. The default port number of the HTTP protocol is 80, and the default port number of the HTTPS protocol is 443, both of which can be omitted.
  4. path: path, indicating the location of the resource in the host.
  5. query: query, indicating additional requirements for resources.
  6. #fragment: Fragment identifier, which represents an anchor point inside the resource, and the browser can jump to the location indicated by it. But this part is not sent to the server.

request object

The HTTP protocol is based on the request-response model . Before HTTP2, the client must initiate the request, the server receives the request, and then responds to the client with the processing result.

When the client sends an HTTP request to the server, it needs to specify a specific URL and HTTP method to tell the server what I want to write or submit. It usually also carries some information, which can be placed in the URL, or in the HTTP Header (header), and if it is submitting data to the server, it can also be placed in the HTTP message entity.

Then the server has to find a way to receive these things. The objects httpin the module requestcontain these things, which can be selectively parsed and used according to their own needs.

Parsing Method

Commonly used HTTP methods are Get, Head, Post, Put, Deleteetc., which can be request.methodobtained directly using .

const server = http.createServer((request, response) => {
    
    
	const method = request.method;
	console.log(method)
	response.end('Hello, World');
});

The browser refreshes the page, and the server prints:

image-20230201174119998

parsing URLs

The composition of the URL is relatively complicated, and request.urlonly the complete URL can be obtained through . For example, browser access http://localhost:3000/list?page=10:

const server = http.createServer((request, response) => {
    
    
    console.log(request.method)
	console.log(request.url)

	response.end('Hello, World');
});

Console prints:

image-20230201174354196

If you want to get a certain part, such as the path path and the query parameter query, you can use the built-in urlmodule:

const http = require('http');
const url = require('url');

const server = http.createServer((request, response) => {
    
    
	
	const urlObj = url.parse(request.url)
	console.log(urlObj)

	response.end('Hello, World');
});

parsemethod to parse the original URL into an object:

image-20230201174634299

Parsing Query

Through the above method, the path and query parameters of the currently requested resource can be obtained . But the query parameter is still a string, which is inconvenient to use.

You can use the built-in querystringmodules to parse, or use URLSearchParamsthe API to parse, or use third-party qs, querystringifyetc. modules to parse. Take the built-in module querystringas an example:

const http = require('http');
const url = require('url');
const qs = require('querystring');

const server = http.createServer((request, response) => {
    
    
	let {
    
     query } = url.parse(request.url)

	query = qs.parse(query)
	console.log(query)

	response.end('Hello, World');
});

You can easily get a query object, which is convenient for reading query parameters:

image-20230201181836136

Parsing Header

The header information of the HTTP request is placed request.headersin the object.

const server = http.createServer((request, response) => {
    
    

	console.log(request.headers);

	response.end('Hello, World');
});

When the browser sends a request, the server will print:

image-20230201183255363

As shown in the figure sec-ch-ua, suchsec-ch-ua-mobile request headers prefixed with , indicate HTTP message headers that are prohibited from being modified by code, and the user agent retains full control over them. sec-For example, what we are familiar with User-Agent, usually the backend will judge the user's system and platform based on it, but it is easy to be modified for camouflage, so it is not safe. sec-ch-uaUser agent information can be safely passed to the server through .

Except for these secure headers, we are very familiar with the rest:

  • host: The request to the host name. Used for virtual host settings.

  • connection: Control the disconnection of network connections. HTTP/1.1 defaults to keep-alive, which means long connection

  • cache-control: Set strong cache.

  • accept: The type of content that the client can receive.

  • accept-encoding: The content encoding available to the client - usually some kind of compression algorithm.

To get information about a specific Header, you can use the square bracket syntax:

const server = http.createServer((request, response) => {
    
    

	console.log(request.headers['content-type']);

	response.end('Hello, World');
});

Parsing the request body

HTTP messages are divided into request messages and response messages . The message consists of these three parts:

  • Start line : divided into request line and status line.
  • Header : Describes the information related to the request, and also describes the information of the entity data.
  • Entity : The data carried.

image-20230201190828182

Some requests, such as file upload and form submission, need to carry some data, which is transmitted in the entity of the message .

HTTP requests just send data, regardless of the type of data. So it will pass in the request header to Content-Typetell the server what format the data carried in this request is in. requestThe object puts the received data in the entity in requst.body. Based on these two points, the data transmitted by the client can be parsed.

In addition, requestthe object is a readable stream. By listening to datathe event, the data transmitted in the entity can be read. When the event is monitored end, it means that the data in the entity has been read and can be parsed.

const http = require('http');
const url = require('url');

const server = http.createServer((request, response) => {
    
    
	const method = request.method;
	const {
    
     pathname } = url.parse(request.url);

    // 处理 Post /user/login
    if(method === 'POST' && pathname === '/user/login') {
    
    

        let arr = [];
        const contentType = request.headers['content-type']
        if (contentType === 'application/json') {
    
    
            // 监听 data 事件,读取实体数据
            request.on('data', (data) => {
    
    
                console.log(data)
                arr.push(data)
            })

            // 监听 end 事件,处理数据
            request.on('end', () => {
    
    
                console.log('传输完毕')
                let json = JSON.parse(Buffer.concat(arr).toString())
                console.log(json)
            })
            // 结束响应
            response.end('Hello, World');
        }
    }
});

server.listen(3000, () => {
    
    
	console.log('服务器启动成功:http://localhost:3000')
})

Taking a form submission for user login as an example, the format is usually used jsonto pass data. Open Postman or ApiPost to send the request:

image-20230201210544034

The server program prints the results as follows:

image-20230201210748466

Summarize

This article introduces requesthow to handle HTTP requests through several commonly used properties of the object:

  • request.method: Get the request method
  • request.url: To get the request URL, you need to use tools such as url, etc. to further analyzequerystring
  • request.headers: Get request header information
  • request.body: Get the request body data, which needs to be Content-Typeparsed into different formats according to

The next article will introduce reponsethe object to complete a completed request processing.

Guess you like

Origin blog.csdn.net/Old_Soldier/article/details/128859879