Here is “to the front-end engineer HTTP series”, remember a big guy once said: “large factory front-end interview requirements for HTTP is higher than CSS”, which shows the importance of HTTP can not be underestimated. This is the second article in the series, “The HTTP Protocol Thing.” This article will cover HTTP protocols, cookies and sessions, HTTP headers/methods/status codes, etc.
Read more about my interview series.
Writing program
-
Parsing from TCP/UDP to DNS
-
HTTP protocol stuff
-
HTTPS / SPDY / HTTP/2 / Websocket
-
JWT
-
Network security
-
Cross domain
-
Caching mechanisms
-
Principles of browsers
-
Final chapter: What happens from entering the URL to rendering the page
The HTTP protocol
HyperText Transfer Protocol (HyperText Transfer Protocol) is an application layer Protocol based on TCP/IP for distributed, collaborative and hypermedia information systems. HTTP is the basis for data communication on the World Wide Web. It is a stateless protocol with a default port of 80. Based on TCP, HTTP defines the request-Response mode, which determines that the communication must be initiated by the browser first.
Without some complexity, browser developers need only a TCP library to handle the network communication part of the browser. We can do an experiment with Telnet.
First connect to the yanceyleo.com host.
telnet yanceyleo.com 80
Copy the code
At this point, the three-way handshake is complete and the TCP connection is established. Type the following and double-click Enter to get the content of the server response. In the following packets, the first line of GET indicates the type of the server to be accessed, which is called method. The following/specifies the resource object requested, also known as the request URI (request-URI); Last is the HTTP version number, which indicates the HTTP version used by the client. The second line is the host name of the request.
GET /HTTP / 1.1Host: yanceyleo.com
Copy the code
HTTP is a connectionless, stateless protocol
HTTP is stateless protocol, which does not save the communication status between request and response, that is, HTTP protocol does not persist the sent request or response. With HTTP, a new response is generated whenever a new request is sent. The protocol itself does not retain all previous request or response message information. This is to process a large number of transactions more quickly, ensuring the scalability of the protocol.
-
There is no connection
Each connection processes only one request, and the server processes one request from the client and then disconnects when the client responds.
-
stateless
Each request sent by the client is considered as a new request by the server, and there is no connection between the last session and the next session.
cookie
Principle of cookies
What is a cookie? We learned above that HTTP is stateless, but as the Web continues to evolve, this stateless nature has its drawbacks. When you log on to a shopping site, you should stay logged on when you jump to other pages on that site. But because HTTP is stateless, information must be stored on the browser side to identify the current user, hence the cookie, which is a file that the browser manages state.
The first time the browser makes a request, the server puts a cookie in response to the request, and the second time the browser makes a request, the cookie is brought over, and the server identifies the user. Note: A single cookie can hold no more than 4K of data, and many browsers limit the number of cookies stored on a site to 20.
Cookie There is a cookie field in the request header and a set-cookie field in the response header.
Cookies are not cross-domain
Cookie itself is used to store some private fields. For security reasons, it must be ensured that cookies are not cross-domain. As an experiment, open https://google.com and type the following code into the developer tools:
document.cookie = 'hello=world; path=/; domain=.baidu.com';
document.cookie = 'world=hello; path=/; domain=.google.com';
Copy the code
Open the Application TAB and find Cookies in the sidebar. You can see that only the ones with domain.google.com have been successfully added.
The attribute of the cookie
Let’s take a look at the server setting cookies through a small login example. First, generate an Express project with express Application Generator. The source code for this example is express-cookies.
Next, by entering the following code in the index.html file, we create an interface for entering a user name and password and send the entered value to the back end via fetch when the button is clicked.
<fieldset>
<legend>Login</legend>
<input id="userName" type="text" placeholder="Please enter user name" />
<input id="userPwd" type="password" placeholder="Please enter your password" />
<button id="loginBtn">The login</button>
</fieldset>
<p>Login Status:<span id="result"></span></p>
<script>
const userName = document.getElementById('userName');
const userPwd = document.getElementById('userPwd');
const loginBtn = document.getElementById('loginBtn');
const result = document.getElementById('result');
loginBtn.addEventListener('click'.function() {
const data = {
userName: userName.value,
userPwd: userPwd.value
};
fetch('/login', {
method: 'POST'.headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(data)
})
.then(res= > {
return res.json();
})
.then(json= > {
result.innerHTML = json.msg;
});
});
</script>
Copy the code
When the user name and password match (assuming both are Yancey), the client is returned with a cookie and json for successful login. Otherwise, json of login failure is returned. The following is the interface that simulates the server login.
router.post('/login', (req, res, next) => {
const body = req.body;
if (body.userName === 'yancey' && body.userPwd === 'yancey') {
/ / set the cookie
res.cookie('yancey'.'success');
res.json({
success: true.msg: 'Login successful'
});
} else {
res.status(401).json({
success: false.msg: 'Wrong username or password'}); }});Copy the code
As you can see from this example, in Express, setCookie is used as follows: Name is passed as the first parameter and value is passed as the second parameter. Note that the browser will escape characters other than metacharacters and semantic characters. Open Chrome’s developer tools and you can see that the cookie has been added to the browser. Or if you type document.cookie in the console, you’ll also see the cookie string.
This is just a simple example of setting cookies. Cookies have seven properties that you can use, and we’ll look at them one by one.
domain
The default is the domain name of the current website. In the following example, the domain is set to yanceyleo.com. Since the front-end page is 127.0.0.1, this cookie does not take effect according to the same-origin policy.
res.cookie('domain'.'domian', { domain: 'yanceyleo.com' });
Copy the code
expires / maxAge
Both of these properties set the expiration time of the cookie. The difference is that Expires accepts a time in the Date format, whereas maxAge accepts a millisecond timestamp. MaxAge is recommended because the latter is more intuitive and easy to use.
Either property can pass a negative value or 0, and if the browser already has a cookie of the same name, it clears it, otherwise it will not be created.
The following example creates a cookie and sets the cookie’s expiration time to one day later.
res.cookie('expires'.'expires', {
expires: new Date(Date.now() + 24 * 60 * 60 * 1000)});Copy the code
Then set a negative value to the cookie, and the cookie is cleared.
res.cookie('expires'.'expires', {
expires: new Date(Date.now() - 8 * 60 * 60 * 1000)});Copy the code
MaxAge is used the same way; it simply passes an expiration time in milliseconds. The following example sets the cookie’s expiration time to 7 days.
res.cookie('maxAge'.'maxAge', {
maxAge: 7 * 24 * 60 * 60 * 1000
});
Copy the code
What about cookies with no expiration date? Cookies that are not set to expire die when you close the site (cookies in this case are like sessions).
httpOnly
When this property is set to true, document.cookie will not get the cookie, but the server will get it as usual. This property can effectively prevent cross-site scripting attacks (XSS). On the topic of network security, we will write an article to talk about it.
res.cookie('httpOnly'.'httpOnly', {
// Can only be accessed by the Web server, which means that the cookie cannot be retrieved by typing document.cookie in the browser to prevent XSS
httpOnly: true
});
Copy the code
path
This property adds the cookie to the specified path, which defaults to /. The following code sets a cookie for the users route (the path will be added even if it does not exist on the server).
res.cookie('path'.'path', {
path: '/users'
});
Copy the code
secure
The cookie is added only when the connection is HTTPS. This property defaults to fasle. Because my local Express protocol is HTTP, this cookie will not take effect.
res.cookie('secure'.'secure', {
secure: true
});
Copy the code
Signed, tamper-proof signature
This property sends an encrypted cookie to the browser and defaults to false. In Express, we can use the cookie-Parser plug-in to create an encrypted cookie. The server verifies whether the cookie has been tampered with by its content and signature
First pass a secret to the cookieParser.
app.use(cookieParser('forcabarca'));
Copy the code
It then returns a cookie after sign.
res.cookie('signed'.'signed', {
signed: true
});
Copy the code
In Express, we can use req. Cookies to get unencrypted cookie objects, and req. SignedCookies to get encrypted cookie objects.
console.log(req.cookies); // { httpOnly: 'httpOnly' }
console.log(req.signedCookies); // { signed: 'signed' }
Copy the code
document.cookie
String to object function
So much for cookies, and finally a document. Cookie string to object function, if you have a better implementation, please leave a comment below.
const formatCookie = cookies= > {
const o = {};
cookies
.split('; ')
.forEach(value= > (o[value.split('=') [0]] = value.split('=') [1]));
return o;
};
Copy the code
session
Session is a mechanism used by the server to record the state of the client. Unlike cookies, sessions are stored on the server. When the client sends a request for the first time (such as a successful login), the server will save the user information in some form on the server. When the client accesses the session again, it only needs to find the state of the client from the session.
Thus, the cookie mechanism determines the identity of the customer by checking the “pass” on the customer, while the session mechanism determines the identity of the customer by checking the “customer list” on the server. A session is a client file created by the program on the server. When a client visits the server, it only needs to query the client file table.
Because HTTP is stateless, a session alone cannot determine which user it is. So the server still sends a cookie with maxAge -1 to the client as a unique identifier for different users.
You can do this by overriding the URL address instead of using cookies. It works by writing the user’s Seesion ID into the URL so that when the browser parses the new URL, it can locate the user.
Both methods ensure that user information is saved to the client in some form. The more advanced localStorage, sessionStorage, IndexedDB is the same principle, not to go into detail here.
The HTTP message
The information used for HTTP interaction is called HTTP packets. Client packets are called request packets and server packets are called response packets. The HTTP message itself is a string of text containing multiple lines of data.
Message format
The figure above clearly shows the formats of request messages and response messages. The text description is as follows.
CR (Carriage Return, Return: hexadecimal 0x0d)
LF (Line Feed, newline: hexadecimal 0x0a)
<! Request message -->
<method>The blank space<request-url>The blank space<version>
<headers>Blank line (CR + LF)<entity-body>
<! -- Response message -->
<version>The blank space<status>The blank space<reason-phrase>
<headers>Blank line (CR + LF)<entity-body>
Copy the code
Compressed packet
The HTTP protocol has a feature called content encoding that can effectively compress the volume of packets. Content encoding specifies the encoding format to be applied to entity content and keeps entity information compressed as is. The encoded entity is received and decoded by the client. Common content encodings are as follows:
-
Identity (Do not compress)
-
Compress (Standard compression for UNIX systems)
-
Gzip (GNU Zip, most common)
-
deflate (zlib)
-
Brotli (Google product, must be a boutique. 37%+ more compression than gzip, my site already uses Brotli, see below)
Split transmit block transmission code
Came back from the HTTP request, produce the streaming data, follow-up of the DOM tree building, CSS calculation, rendering, synthesis, paint, are as much as possible output flow processing in the previous step: don’t need to wait until the end of a step completely namely, began to deal with the output of the previous step, so we are browsing the web, a page will see step by step.
Essentially, during HTTP communication, the browser cannot display the requested page until all of the requested encoded entity resources have been transferred. When transferring large amounts of data, the browser can gradually display the page by dividing the data into chunks. This ability to block the body of an entity is called Chunked Transfer Code.
The chunking transfer encoding divides the entity body into blocks, each of which is sized in hexadecimal notation, and the last block of the entity body is marked with 0 (CR+LF). The entity body that uses the chunking transfer encoding is decoded by the receiving client and reverts to the entity body before encoding.
HTTP header
In the previous section, we talked about HTTP packets, which are composed of three parts: packet header, blank line, and packet body.
The header of a request packet consists of the method, URL, HTTP version, and HTTP header field.
The header of a response packet consists of the HTTP version, status code, and HTTP header field.
Header field type
-
General Header Field Indicates the Header used by both the request and response packets.
-
Request Header Field Indicates the Header used to send Request packets from the client to the server. This section provides additional information about the request, client information, and priority of the response.
-
Response Header Field Indicates the Header used to return Response packets from the server to the client. Additional content added to the response also requires the client to attach additional content information.
-
Entity Header Field The Header used for the Entity part of the request message and response message. Added entity-related information such as when the resource content was updated.
End-to- End and Hop-by- Hop headers
HTTP header fields are defined as the behavior of cached and uncached proxies, divided into end-to-end headers and item-by-item headers.
The end to end header is forwarded to the final recipient of the request/response and must be stored in the response generated by the cache, and it must be forwarded.
The header to the hop-by-hop header is only valid for a single forward and will not be forwarded again due to caching or proxy. Versions after HTTP/1.1 require a Connection header field if hop-by-hop headers are used. Among them, Connection, Keep-alive, proxy-Authenticate, proxy-authorization, Trailer, TE, Transfer-Encoding and Upgrade are hop by hop heads. Everything else is end-to-end.
Generic header field
Cache-Control
This field controls how the cache works and takes multiple arguments separated by commas.
instruction | parameter | type | instructions |
---|---|---|---|
no-cache | There is no | Both request/response have this field | If the request contains this field, it indicates that the client does not accept caching. If the server contains this field, verify its validity before caching it |
no-store | There is no | Both request/response have this field | The request or any corresponding content is not cached. The no-cache response is actually stored in the local cache, whereas the no-store response is not cached locally at all |
max-age | The unit is seconds. Required | Both request/response have this field | When the cache time is less than this value, the client accepts the cached resource, otherwise requests the source server, and this directive takes precedence over Expires |
max-state | The unit is second. Parameters can be omitted | Only the request owns this field | As long as this field is present, the client can accept an expired cache |
min-fresh | The unit is seconds. Required | Only the request owns this field | This directive requires the cache server to return cached resources that have not been cached for at least the specified time |
no-transform | There is no | Both request/response have this field | The cache is not allowed to change the media type of the entity body, either in the request or in the response |
only-if-cached | There is no | Only the request owns this field | Indicates that the client will only request a return if the cache server has cached the target resource locally |
cache-extension | – | Both request/response have this field | New instruction extension |
public | There is no | Only the response has this field | The corresponding cache can be provided to any client |
private | Can be omitted | Only the response has this field | Returns a response only to a specific user |
must-revalidate | There is no | Only the response has this field | It is cacheable, but you must validate again to the source server |
proxy-revalidate | There is no | Only the response has this field | The intermediate cache server is required to validate the cached response |
s-maxage | The unit is seconds. Required | Only the response has this field | In contrast to max-age, this directive applies only to public servers |
Connection
Connection is used to control header fields that are no longer forwarded to agents and to manage persistent connections. HTTP/1.1 is a persistent Connection by default, and when the server explicitly disconnects, Connection is set to Close.
Date
Date Indicates the Date and time when a packet is created. It is in the following format.
date: Sun, 05 May 2019 02:05:37 GMT
Copy the code
Trailer
This field pre-states which header fields are recorded after the packet body and can be used for HTTP/1.1 block transfer encoding.
Transfer-Encoding
This field specifies the encoding mode used to transmit the packet body. The HTTP/1.1 encoding mode is valid only for block encoding.
Upgrade
This field is used to check whether HTTP or other protocols can communicate with a higher version. This field is used together with the Connection field. The following example asks if the TLS/1.0 protocol is available. For requests with the Upgrade field attached, the server can return a status code of 101.
connection: upgrade
upgrade: TLS / 1.0Copy the code
Via
This field traces the transmission path of request and response packets between the client and the server.
Request header field
Accept
This field informs the server of the media types that the user agent can handle and the relative priority of the media types. Where, q represents the weight. The following example shows that the client can accept either plain text or HTML and has a willingness (weight) of 0.3 to accept plain text.
Accept: text/plain; Q = 0.3, text/HTMLCopy the code
Accept-Charset
This field informs the server about the character set supported by the user agent and the relative priority of the character set. This field applies to server-driven negotiation of the content negotiation mechanism. If the server does not provide any character set for this field, error 406 is reported, so try not to use this field (I have tried several sites that do not have this field). The following example shows that the client supports UTF-8 and ISO-8859-1, and utF-8 is preferred.
Accept-Charset: utf-8, iso-8859-1; Q = 0.5Copy the code
Accept-Encoding
This field tells the server which header compression algorithm the client can use. The packet compression methods described above are not described here.
Accept-Encoding: gzip, deflate, br
Copy the code
Authorization
This field is used to tell the server the authentication information of the user agent. The following is a scenario of my blog backend management system. When requesting an interface that requires authentication, authentication information needs to be attached to the request header.
Authorization: Bearer JWT_TOKEN
Copy the code
Expect
Clients use Expect to tell the server that a particular behavior is expected. When the server fails to understand the client’s expectations and an error occurs, the 417 status code is returned.
This field is related to the status code 100. Clients waiting for a response to the status code 100 need to specify Expext: 100-continue when a request is made. The purpose of this status code is to allow the client to determine whether the server is willing to receive the request before sending the request body.
Expect: 100-continue
Copy the code
From
This field is used to tell the server the Email address of the user using the user agent.
Host
When multiple virtual hosts are assigned to a single server, the Host field can be used to determine the corresponding Host.
Host: www.abc.com
Copy the code
If-Match
Request fields of the form IF-xxx are called conditional requests. The server will execute the request only if the condition is true after receiving the request.
The server compares the field value of if-match with the ETag value of the resource. The request is executed only when the two values are the same. Otherwise, the 412 status code is returned. If the if-match field is *, the server ignores the ETag value and processes the request as long as the resource exists.
If-Match: W/"pqxe5g29m4"
Copy the code
If-None-Match
In contrast to if-match, the server matches the field value of if-none-match with the ETag value of the resource, and only executes the request If the two are inconsistent. Using this field in the GET and HEAD methods retrieves the latest resource.
If-Modified-Since
If the resource is updated after the date and time specified in the if-Modified-since field, the server accepts the request. If the resource has not been updated, the 304 status code is returned.
The value of this field is compared to the last-modifie field of the response header field. In the following example, it is clear that the Last modification time is newer than if-Modified-since, so the new resource will be responded to.
// Request header if-modified-since: Fri, 01 May 2019 11:20:04 GMT // Response header last-modified: Fri, 03 May 2019 11:20:04 GMTCopy the code
If-Unmodified-Since
The server accepts the request only If the resource has not been updated after the date and time specified in the if-Modified-since field. If the resource is updated after this point, a 412 error is reported.
If-Range
The value of this field is compared to the ETag or Date in the corresponding header. If the value is consistent, it is processed as a range request and status code 206 is returned. Otherwise, all resources are returned.
Range
For scope requests that fetch only part of the resource, including the header field Range tells the server the specified scope of the resource. The server that receives a request with a Range field returns a response with status code 206 after processing the request. When the range request cannot be processed, the 200 status code and all resources are returned.
Range: bytes=5001-10000
Copy the code
Proxy-Authorization
This field is used to tell the proxy server the authentication information of the user agent.
Referer
Tell the server where the request URI originated. For example, if I request an image from AliOSS on my blog www.yanceyleo.com, the request header from the AliOSS server will include:
Referer: https://www.yanceyleo.com
Copy the code
The correct spelling is referrer, of course, but referer is still used today. Think of a lyric: “in the wind and sand all over the sky, looking at you far away, I actually sad can’t own (already).”
TE
This field tells the server which transport encoding and relative priority the client can process the response. It is similar to Accept-encoding, but is used to transmit Encoding. In addition to specifying the transport encoding, you can also specify the block-transport encoding that accompanies the Trailer field.
TE: gzip, delate; Q = 0.5TE: trailers
Copy the code
User-Agent
This field does not know directly to redo it, here do not go to repeat, directly look at the example.
User-Agent: Mozilla / 5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36Copy the code
Response header field
Accept-Ranges
This field is used to tell the client whether the server can process a range request, specified as bytes if it can and None otherwise.
Accept-Ranges: bytes
Copy the code
Age
This field is used to tell the client how long ago the source server created the response, and the field value is in seconds. If the server that creates the response is a cache server, the Age value refers to the CDN from the time when the cached response initiates authentication again to the time when the authentication is complete.
Age: 500
Copy the code
ETag
ETag is a string that uniquely identifies resources. The server assigns ETag values to each resource. When the resource is updated, the ETag value needs to be updated.
ETag has strong ETag value and weak ETag value. The former means that the value of an entity changes no matter how slight a change it makes. Weak ETag is only used to indicate whether the resources are the same. The ETag value is changed only when the resource is fundamentally changed. The weak ETag field value is marked with W. The former is like using {deep: true}.
The following code is an ETag for an image, obviously an image change means a complete change of resource, so a strong ETag is used.
ETag: "F8F155B13C6DA43723EEDE3EDBBB4D28"
Copy the code
The following code requests an ETag for a data interface, which in most cases will not change radically, so weak ETAGS are used.
etag: W/"300af-7JrdwEcHHeXMqn/UCrMO0zsO0SY"
Copy the code
Location
The Location field directs the response recipient to a resource at a different Location from the request URI, and is typically used in combination with the 3XX status code.
Location: https://yanceyleo.com
Copy the code
Proxy-Authenticate
This field sends the authentication information requested by the proxy server to the client.
Retry-After
This field tells the client how long after the request should be sent again. When the server error message 503, if the server knows when it can be restored, it should inform the client through this field. The field value of this field can be a specific date and time or the number of seconds since the response was created.
Retry-After: Sat, 04 May 2019 11:26:52 GMT
Copy the code
Server
This field is also a common field that tells the client the name of the Web server. Let’s say I use CloudFlare’s CDN, so the server looks like this.
server: cloudflare
Copy the code
vary
This field can be used to control the cache, and its field values receive a list of other header field names.
vary: Accept-Encoding,Cookie
Copy the code
In the example above, the source server sends the Vary field to the proxy server, which can cache only accept-encoding and cookies.
WWW-Authenticate
This field informs the client about the authentication scheme applicable to access the resource specified by the request URI and the challenge with a parameter prompt.
Entity head field
Allow
This field informs the client of all supported HTTP request methods. When the server receives an unsupported HTTP method, it returns the 405 status code and writes all supported HTTP methods to the header field.
Allow: GET, PUT
Copy the code
Content-Encoding
Inform the client of the content encoding method used by the server.
content-encoding: br
Copy the code
Content-Language
Inform the client of the natural language used by the entity body.
content-language: zh-CN
Copy the code
Content-Length
This field indicates the size of the body part of the entity, in bytes.
Content-Length: 4871261
Copy the code
Content-MD5
This field is used to check whether the integrity of the packet body is maintained during transmission and confirm the arrival of the transmission. The server executes the MD5 algorithm on the packet body to obtain a 128-bit binary number and writes the result into the Content-MD5 field after base64 encoding. Because the HTTP header cannot record binary values, it needs to be processed through Base64. After receiving the response, the client executes the same MD5 algorithm on the packet body. The accuracy of the packet body can be judged by comparing the calculated value with the field value.
Content-MD5: +PFVsTxtpDcj7t4+27tNKA==
Copy the code
Content-Range
This field tells the client which part of the entity returned as a response conforms to the scope request, and the field value is in bytes.
Content-Type
A very common field specifying the media type of an object within an entity body.
content-type: application/json; charset=utf-8
Copy the code
Expires
This field tells the client the date the resource failed, and a copy of the response is kept until the specified Expires time. After the specified time has elapsed, the cache server turns to the source server to request the resource when the request is sent. If the header field cache-control has a specified max-age, max-age is processed first.
The caching mechanism will be covered in more detail in the next chapter.
Last-Modified
This field specifies when the resource was last modified. In general, this value is the time when the request-URI specified the resource was modified.
HTTP method
The method name | describe |
---|---|
GET | A GET request displays the resource specified by the request. In general, the GET method should only be used for reading data and should not be used for non-idempotent operations that have side effects. What it expects should be and should be safe and idempotent. By security, I mean that the request does not affect the state of the resource. |
HEAD | The HEAD method, like the GET method, makes a request to the server for a specified resource. However, when the server responds to a HEAD request, it does not pass back the content portion of the resource: the response body. This way, we can get the response header information from the server without transferring the entire content. The HEAD method is often used by clients to view server performance. |
PUT | A PUT request uploads its latest content to the specified resource location. The PUT method is idempotent. This method allows the client to send the latest data of the specified resource to the server instead of the content of the specified resource. |
POST | A POST request submits data to a specified resource. The request server processes the data, such as form data submission and file upload, in the request body. The POST method is non-idempotent because the request may create a new resource or/and modify an existing resource. |
TRACE | The TRACE request server displays the received request information. This method is mainly used to test or diagnose HTTP requests. |
OPTIONS | OPTIONS requests are similar to HEAD and are used by clients to check server performance. This method will ask the server to return all HTTP request methods supported by the resource. This method will replace the resource name with ‘*’ and send an OPTIONS request to the server to test whether the server is functioning properly. When the XMLHttpRequest object of JavaScript performs CORS cross-domain resource sharing, it uses the OPTIONS method to send a sniffing request to determine whether there is access to the specified resource. |
DELETE | A DELETE request is used to ask the server to DELETE a Resource identified by the Uniform Resource Identifier (URI) requested. The specified resource is deleted after a DELETE request, and the DELETE method is idempotent. |
PATCH | PATCH method appeared relatively late, it was defined in RFC 5789 standard in 2010. PATCH requests are similar to PUT requests and are used to update resources. The differences are as follows: 1.PATCH is generally used for partial resource update, while PUT is generally used for overall resource update. 2. When a resource does not exist, PATCH creates a new resource, and PUT only updates the existing resource. |
CONNECT | The CONNECT method is reserved for HTTP/1.1 and enables the connection to be piped to a proxy server. Typically used for communication between SSL encrypted server links and unencrypted HTTP proxy servers. |
GET, HEAD, PUT, and DELETE are idempotent methods, while POST is not.
The HTTP status code
The HTTP status code is responsible for representing the return result of the CLIENT’S HTTP request, marking the normal processing of the server, and notifying the error.
1xx Indicates the information status code
Status code | Status code English name | describe |
---|---|---|
100 | Continue | The server received the initial portion of the request, asking the client to continue. |
101 | Switching Protocols | The server switches protocols based on client requests |
The 1xx status code represents a temporary response, consisting only of a status line and an optional header, terminated by a blank line. No headers are required for this class of status codes. This class of status codes was introduced in HTTP/1.1, so the server is prohibited from responding to 1XX status codes to HTTP1.0 clients.
For the 100 (Continue) status code, the client should Continue with its request. This transient response is used to inform the client that the initial portion of the request has been received and not rejected by the server. The client should continue to send the remaining requests and ignore the response if the request has already been completed. The server must send a final response when the request completes.
The main purpose of the 100 status code is to allow the client to determine whether the server is willing to receive the request (via the request header) before sending the request body. In some cases, it is inappropriate or inefficient for a client to send a request body if the server rejects the request without looking at it.
2xx Success status code
Status code | Status code English name | describe |
---|---|---|
200 | OK | The request succeeds, and the response body contains concrete data. Most commonly, GET and POST requests return this status code. |
201 | Created | Has been created. Normal PUT requests return this status code. |
202 | Accepted | The server has received the request but has not completed processing. |
203 | Non-Authoritative Information | Unauthorized information. The request was successful, but the meta information is not on the original server, but a copy of the resource. This can occur if there is a copy of a resource on an intermediate node, but it cannot or does not validate the resource-related meta-information it emits. |
204 | No Content | The response packet contains no body part. A normal DELETE request would return this status code. |
205 | Reset Content | Responsible for telling the browser to remove all HTML elements from the current page. |
206 | Partial Content | A partial or Range request was successfully executed. The client can request files in a range specified in the header. The status response header must contain content-range, Date, and either ETag or Content-Location. |
The 206 status code is typically encountered when downloading large files. It indicates that the request was successful and that the body contains the requested data Range specified at the request’s Range header. In the image below, my blog returns a 206 status code when it retrieves an audio file.
3xx Redirection status code
Status code | Status code English name | describe |
---|---|---|
300 | Multiple Choices | The client requests urls that actually point to multiple resources. The client can find a list of resources in the response. |
301 | Moved Permanently | The requested URL has been removed. The Location header of the response contains the current Location. |
302 | Found | Similar to 301, the client should use the temporary URL in the response this time and use the previous URL for future requests. |
303 | See Other | Tell the client to use a different URL to get the resource. Its main purpose is to allow the response to a POST request to direct the client to a resource. |
304 | Not Modified | If the client sends a conditional GET request but the resource is not modified, you can use this status code to indicate that the resource is not modified. |
305 | Use Proxy | This resource must be accessed through a proxy, which is given in the Location header. It is important to note that when the client receives this state, it should not assume that all requests go through the broker. |
307 | Temporary Redirect | Same as 302. |
4XX Client error status code
Status code | Status code English name | describe |
---|---|---|
400 | Bad Request | Tell the client that it sent an incorrect request. |
401 | Unauthorized | Returns with the appropriate header, telling the client to authenticate before requesting it. |
403 | Forbidden | The request was denied. |
404 | Not Found | The server could not find the requested URL. |
405 | Method Not Allowed | The client requested the URL using an unsupported method. Allow should be used in the header to inform the client of the correct method. |
406 | Not Acceptable | The server could not provide a response that matched the values specified in the Accept-Charset and Accept-language headers |
407 | Proxy Authentication Required | Proxy servers require client authentication. |
408 | Request Timeout | The server can close the link if the client takes too long to complete the request. |
409 | Conflict | The server thinks the request may cause a conflict. The response body should contain a description of the conflicting principal. |
410 | Gone | This is similar to 404, except that the server once owned the resource and has since been removed. |
411 | Length Required | The server requires that the request packet contain the Content-Length header. |
412 | Precondition Failed | The client initiates a conditional request, and some of the conditions fail. |
413 | Request Entity Too LargeRequest Entity Too Large | The client sends a larger body than the server can hope to handle. |
414 | Request URI Too Long | The URL is too long. |
415 | Unsupported Media Type | The server could not understand or support the type of content sent by the client. |
416 | Requested Range Not Satisfiable | The requested scope is invalid or cannot be satisfied. |
417 | Expectation Failed | The request header contains Expect expectations, but the server cannot meet them. |
429 | Too Many Requests | Sending too many requests in too short a time |
431 | Request Header Fields Too Large | The request header is too large |
5xx Server error status code
Status code | Status code English name | describe |
---|---|---|
500 | Internal Server Error | The server encountered an error that prevented it from serving. |
501 | Not Implemented | A client initiated a request that was beyond the server’s capabilities, for example using an unsupported method. |
502 | Bad Gateway | Invalid gateway. Usually it is not the upstream server that is down, but the protocol used by the upstream server does not agree to exchange data. |
503 | Service Unavailable | The server is temporarily unavailable. If the server knows when the service will be available, it can add a retry-after header to the response header. |
504 | Gateway Timeout | Similar to 408, except that the response comes from a gateway or proxy that timed out while waiting for another server response to respond to its request. |
505 | HTTP Version Not Support | The server received a request using a protocol version it did not support. |
conclusion
This article focuses on the HTTP protocol and its connectionless, stateless nature, which leads to cookies and sessions. Then it introduces HTTP headers, methods and status codes. The next article will focus on HTTP caching, so stay tuned.
Welcome to follow my wechat public number: the front of the attack
reference
Illustrated HTTP by Ueno
The use of cookies and cookie-parser in Express
Talk about the cookie
Let’s get cookie straight
This time, let’s dig a little deeper – HTTP packets
HTTP status code 100
You know the 3XX status code