The Http status code

Status code meaning
1XX The request is being processed
2XX The request was processed successfully
3XX Requests require additional actions, such as redirects
4XX The request cannot be processed because of a client error
5XX Server processing error

2XX

Status code The reason the phrase meaning
200 OK The request was processed normally
204 NO CONTENT The request succeeds, but the response message does not contain the entity body
206 Partial Content Only the part that requested the resource is returned

204: The option request, for example, is usually used as a pre-request for a formal request. This request only needs to confirm whether subsequent requests can be accepted, that is, only one result is required, and nothing else is returned.

206: In HTTP requests, add a Range header to indicate a Range request, for example

'Range': byte=5001-10000 // Indicates 5001-10000 bytes of the resource to be requested this timeCopy the code

In this case, if the server accepts the range request and processes it successfully, 206 is returned, and in the header of the response:

'Content-Range':bytes 5001-10000/10000// Indicates that the entire resource contains 10000 bytes. This time, 5001-10000 bytes are returnedCopy the code

3XX

Status code The reason the phrase meaning
301 Moved Permanently The resource has been permanently redirected
302 Found Resources are temporarily redirected to location
303 See Other Resource useGETAccess the location for temporary redirection
304 Not Modified The resource is not changed and can be used directly with the cache
307 Temporary Redirect Strictly restrict redirects from being allowedPOSTtoGET

The only difference between 301 and 302 is that one is temporary and the other is permanent.

4XX

Status code The reason the phrase meaning
400 Bad Request Syntax error in request
401 Unauthorized Uncertified
403 Forbidden Access forbidden means no access permission
404 Not Found The server did not find the requested resource

5XX

Status code The reason the phrase meaning
500 Internal Server Error Server failure
503 Service Unavailable The server is temporarily unavailable

The cache

Each time the browser initiates a request, it first looks up the result of the request and the cache identifier in the browser cache

Each time the browser receives the result of the returned request, it stores the result and the cache id in the browser cache

Strong cache

The strong cache does not send a request to the server, but reads resources directly from the cache. In the Network option of the Chrome console, you can see that the request returns a status code of 200 and Size displays from Disk cache or from Memory cache. Strong caching can be implemented by setting two httpHeaders: Expires and cache-Control.

1. Expires

Cache expiration time, used to specify the expiration time of resources, is a specific point in time on the server. That is, Expires=max-age + request time needs to be used in combination with last-Modified. Expires is a Web server response header field that tells the browser in response to an HTTP request that the browser can cache data directly from the browser before the expiration date without having to request it again. Expires is a product of HTTP/1 and is limited to local time, which can invalidate a cache if you change it. Expires: Wed, 22 Oct 2018 08:41:00GMT Indicates that the resource will expire after Wed, 22 Oct 2018 08:41:00GMT and needs to be requested again.

2. Cache-Control

In HTTP/1.1, cache-control is the most important rule and is used to Control web page caching. For example, cache-control :max-age=300 means that the strong Cache will be hit if the resource is reloaded within 5 minutes of the correct return time of the request (which the browser records). Cache-control can be set in either the request header or the response header, and can be combined with multiple instructions:

instruction role
public Responses can be cached by both client and proxy servers
private Responses can only be cached by clients
max-age=30 The cache expires after 30 seconds and needs to be re-requested
s-maxage=30 covermax-age, the effect is the same, only in the proxy server effect
no-store No response is cached
no-cache The resource is cached but invalid immediately. Next time, a request will be sent to verify whether the resource has expiredNegotiate the cacheuse
max-stale=30 Within 30 seconds, use the cache even if it expires
min-fresh=30 Expect the latest response within 30 seconds

Details:

  • Public: All content will be cached (both client and proxy servers can be cached). Specifically, the response can be cached by any intermediate node, such as Browser<–proxy1<–proxy2<–Server. The proxy in the middle can cache resources, for example, the next time proxy1 requests the same resource, proxy1 directly gives its cache to Browser instead of asking For it from Proxy2.

  • Private: All content can be cached only by the client. The default value of cache-control. For Browser<–proxy1<–proxy2<–Server, proxy will send data returned by Server to Proxy1 without caching any data. The next time Browser requests it again, the proxy forwards the request instead of giving cached data to itself.

  • No-cache: indicates the content of the client cache. Whether to use the cache requires negotiation cache. Does not use cache-control Cache Control for pre-validation, but uses the Etag or Last-Modified field to Control the Cache.

    Note that the name no-cache is a bit misleading. This does not mean that the browser will no longer cache data, but that the browser needs to make sure that the data is consistent with the server before using the cache.

  • No-store: All content is not cached, that is, neither mandatory cache nor negotiated cache is used

  • Max-age: max-age= XXX (XXX is numeric) indicates that the cache contents will expire after XXX seconds

  • S-maxage (unit: s) : the same as max-age, only in the proxy server (such as CDN cache). For example, when s-maxage=60, during this 60 seconds, even if the content of the CDN is updated, the browser will not request it. Max-age is used for normal caching, while s-maxage is used for proxy caching. S-maxage has a higher priority than max-age. Max-age and Expiresheader are overridden if s-maxage is present.

  • Max-stale: indicates the maximum expiration time that can be tolerated. The max-stale directive indicates that the client is willing to accept a response that has expired. If a max-stale value is specified, the maximum tolerance time is the corresponding number of seconds. If not specified, the browser is willing to receive any response from age (age represents the difference between the time the response was generated or validated by the source site and the current time).

  • Min-fresh: Minimum level of freshness that can be tolerated. Min-fresh indicates that the client is unwilling to accept a response whose freshness is less than the sum of the current age plus the time set by Min-Fresh.

3. Compare Expires and Cache-control

The difference is that Expires is a product of HTTP1.0 and cache-Control is a product of HTTP1.1. If both exist, cache-Control takes precedence over Expires. In some environments where HTTP1.1 is not supported, Expires can be useful. So Expires is an outmoded object that currently exists as a way to write compatibility.

Strong caches Determine whether or not the cache is cached based on whether or not the server side file has been updated after a certain time or period, which may result in the loading file is not the latest content on the server side, so how do we know whether the server side content has been updated? Here we need to use a negotiated cache strategy.

Negotiate the cache

Negotiation cache is a process in which the browser sends a request to the server with the cache ID after the cache is invalid, and the server decides whether to use the cache based on the cache ID. There are two main situations:

  • The negotiation cache takes effect304andNot Modified
  • Negotiation cache invalid200And request results

The negotiated cache can be Modified and ETag by setting two HTTP headers.

1. The last-modified and If – Modified – Since

When the browser accesses the resource for the first time and the server returns the resource, the last-Modified header is added to the response header, whose value is the Last modification time of the resource on the server. The browser caches the file and header after receiving it.

Last-Modified: Fri, 22 Jul 2016 01:47:00 GMT
Copy the code

The next time the browser requests the resource, the browser detects a last-Modified header and adds if-modified-since, which is the last-modified value; When the server receives the resource request again, it compares the value in if-modified-since with the last modification time of the resource in the server. If there is no change, it returns 304 and an empty response body, reading directly from the cache. If the time of if-modified-since is less than the time of the last modification of the resource on the server, the file has been updated, and the new resource file and 200 are returned.

But last-Modified has some drawbacks:

If the cache file is opened locally, last-Modified is Modified even if the file is not Modified. The server cannot match the cache and sends the same resource. Because last-Modified can only be measured in seconds, if the file is Modified in an imperceptible amount of time, the server will assume that the resource is still a hit and will not return the correct resource. Since the cache is not sufficient based on the file modification time, can the cache policy be determined directly based on the file content modification? Hence the ETag and if-none-match in HTTP/1.1;

2. The ETag and If – None – Match

An Etag is a unique identifier (generated by the server) that is returned to the current resource file when the server responds to a request. The Etag is regenerated whenever the resource changes. The next time the browser loads a resource and sends a request to the server, it will place the last returned Etag value in if-none-match in the request header. The server can determine If the resource has been modified relative to the client by comparing if-none-match with the ETag of the resource on the server. If the server finds that the ETag does not match, it sends the new resource (including the new ETag) to the client in a regular GET 200 packet return. If the ETag is consistent, 304 is returned to inform the client to use the local cache directly.

3. Compare the two

  • First, Etag is superior to Last-Modified in accuracy.

    Last-modified time is in seconds. If a file changes several times within a second, their last-Modified time is not actually Modified, but Etag changes each time to ensure accuracy. If the server is load-balanced, the last-Modified generated by each server may also be inconsistent.

  • Second, in terms of performance, Etag is inferior to Last-Modified, because last-Modified only takes time to record, whereas Etag requires the server to compute a hash value through an algorithm.

  • Third, server verification takes Etag as the priority.

Mandatorized caching takes precedence over negotiated caching. If mandatorized caching (Expires and cache-control) is in effect, the Cache is used directly. If not, the negotiation cache (last-modified/if-modified-since and Etag/if-none-match) is implemented. The negotiation cache is determined by the server whether to use the cache or not. If the negotiation cache is invalid, the request cache is invalid and 200 is returned. Return the resource and cache id to the browser cache; If it takes effect, return to 304 and continue to use the cache.

The cache policy is applied in actual scenarios

1. Frequently changing resources

Cache-Control: no-cache
Copy the code

For resources that change frequently, cache-control: no-cache is used to make the browser request the server each time, and then ETag or Last-Modified is used to verify that the resource is valid. This does not save the number of requests, but it can significantly reduce the size of the response data.

2. Resources that are not constantly changing

Cache-Control: max-age=31536000
Copy the code

Such resources are typically processed by setting their cache-control to a large max-age=31536000(a year) so that subsequent browser requests for the same URL will hit the forced Cache. In order to solve the update problem, dynamic characters such as hash and version number need to be added to the file name (or path), and then dynamic characters need to be changed to change the reference URL, so that the previous mandatory cache is invalidated (it is not immediately invalidated, but is no longer used).

Content reference: The browser cache mechanism

Cookie implementation mechanism

A Cookie is a small text file stored by the client as a series of key-value pairs. The Cookie is set by the HTTP server and stored in the browser. When the user visits other pages, the Cookie is attached to the HTTP request.

  1. The browser makes an HTTP request to a URL (it can be anything, such as GET a page, POST a login form, etc.)
  2. The corresponding server receives the HTTP request and calculates the HTTP response that should be returned to the browser.
  3. Add a set-cookie field to the response header whose value is the Cookie to Set.
  4. The browser receives an HTTP response from the server.
  5. When the browser finds the set-cookie field in the response header, it stores the value of the field in memory or on hard disk.

The value of the set-cookie field can be a number of item cookies, each of which can specify an expiration time. The default expiration time is when the user closes the browser.

  1. When the browser sends an HTTP request to the server next time, the Cookie set by the server is appended to the Cookie header field of the HTTP request.

The browser can store cookies under multiple domains, but only sends cookies once specified by the currently requested domain, which can also be specified in the set-cookie field.

  1. When the server receives the HTTP request and finds a Cookie field in the request header, it knows it has dealt with the user before.
  2. Expired cookies are deleted by the browser.

In summary, the server instructs the browser to save the Cookie through the set-cookie response header field, and the browser tells the server about the previous status through the Cookie request header field. Cookies contain several key-value pairs, each of which can set an expiration time.