Preface
The previous article introduced http
the basic usage of the module, which mainly calls the createServer
and listen
methods to create and start services. To handle specific HTTP requests, you need to createServer
write something in the method. This article introduces two core objects request
and response
.
URL
The HTTP protocol was first designed just to obtain an HTML document on the Internet. With subsequent development, resources on the Internet have become more and more abundant, and the types have evolved from 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 the URL - Uniform Resource Locator (Uniform Resource Locator) .
The following is the composition of the URL:
1.scheme: It is what we often call "protocol", which is translated as "scheme" in "HTTP Authoritative Guide". Commonly used protocols include HTTP, FTP, SMTP, etc.
2.user:password@: Indicates the user and password to access this resource. No verification is required for public network resources. Even if necessary, it would not be used like this, 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. 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 a protocol based on the request-response model . Before HTTP2, the client must initiate a request, the server must receive the request, and then respond 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. If data is submitted to the server, it can also be placed in the HTTP message entity.
Then the server must find a way to receive these things. The objects http
in the module request
contain these things and can be selectively parsed and used according to your own needs.
Parse Method
Commonly used HTTP methods include Get
, Head
, Post
, Put
, Delete
etc., which can be request.method
obtained 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:
Parse URL
The URL composition is relatively complex, and request.url
only 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:
To get a certain part, such as path, query, you can use url
a module or URL
object. For example, using url
the module:
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');
});
parse
Method that parses the original URL into an object:
Parse Query
Through the above method, you can get the path and query parameters of the currently requested resource . But the query parameter is still a string, which is inconvenient to use.
You can use built-in querystring
modules to parse, or use URLSearchParams
API to parse, or use third-party qs
, querystringify
etc. modules to parse.
Take the built-in module querystring
as 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 to facilitate reading query parameters:
Parse Header
The header information of HTTP requests is placed request.headers
in the object.
const server = http.createServer((request, response) => {
console.log(request.headers);
response.end('Hello, World');
});
The browser sends a request, and the server will print:
As shown in the figure sec-ch-ua
, request headers sec-ch-ua-mobile
prefixed sec-
with , indicate that HTTP headers that are not modified by code are prohibited, and the user agent retains full control over them. For example, as we are familiar with User-Agent
, usually the backend will judge the user's system and platform based on it, but it can be easily modified to disguise it, so it is unsafe. sec-ch-ua
User agent information can be safely passed to the server through .
In addition to these safe headers, we are all very familiar with the rest:
- host: The host name of this request. Used for virtual hosting setup.
- connection: Controls the disconnection of network connections. HTTP/1.1 defaults to
keep-alive
, indicating a long connection - cache-control: Set strong cache.
- accept: The type of content the client can receive.
- accept-encoding: The content encoding method available to the client - usually some kind of compression algorithm.
To get information about a specific Header, you can:
const server = http.createServer((request, response) => {
console.log(request.headers['content-type']);
response.end('Hello, World');
});
Parse request body
HTTP messages are divided into request messages and response messages . The message consists of these three parts:
- Starting line : divided into request line and status line.
- Header : Describes information related to the request, and also describes information about entity data.
- Entity : carried data.
Some requests, such as file upload and form submission, need to carry some data, and these data are transmitted in the entity of the message .
HTTP requests only send data, regardless of the type of data. Therefore, the server will be informed by in the request header Content-Type
what format the data carried in this request is. request
The object will place the data in the received entity requst.body
in . Based on these two points, the data transmitted by the client can be parsed.
In addition, request
the object is a readable stream, and by listening to data
events, 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 user login form submission as an example, json
data is usually passed in the format. Open Postman or ApiPost to send the request:
The server program prints the following results:
at last
Recently I found a VUE document that summarizes various knowledge points of VUE and compiled it into "36 Tips You Must Know for Vue Development". The content is relatively detailed, and the explanations of various knowledge points are also very good.
Friends in need can click on the card below to receive it and share it for free