In the last article we discussed the TCP three-way handshake, HTTP request headers, response headers, content-Type fields, how to use Node to control these fields, and more. This article will start with HTTP status codes and discuss common HTTP methods for writing and controlling caching.

When we debug an interface, the number we like is 200, or we don’t like anything else. For example, 404401403500. There are countless articles about status codes, which are essentially a matter of memory. I will simply list a list of common status codes, as follows:

The requester should Continue to make requests. The server returns this code to indicate that it has received the first part of the request and is waiting for the rest.

101 Switching Protocols The requester has asked the server to switch Protocols, the server has acknowledged and is ready to switch.

----

2 xx success

200 OK (success) The server successfully processed the request. Typically, this means that the server has provided the requested web page.

The server successfully processed a Partial GET request.

----

3 xx redirection

The requested page has Not been Modified since the last request. When the server returns this response, the web page content is not returned.

----

4XX Client error

400 Bad Request The server does not understand the syntax of the Request.

401 Unauthorized Requests require authentication. The server may return this response for a web page that requires login.

403 Forbidden The server rejects requests.

----

5XX Server error

500 The server has an internal error

Copy the code

In our own server, you can set any status code you want! There may be pits ^-^, take a look at the server code:

Res.statuscode = 200 // you can modify the statusCode as you like.

Res.end (' My first server ')

Copy the code

We won’t look at the other sizes. Let’s look at 200 and 304. When the browser makes a get request and the request succeeds, it returns a status of 200, as shown in the following figure:

It seems perfect, but every request wastes network resources, and some things only need to be requested once. We like that it can be cached down to improve access speed and save network resources.

Caching, you have to fetch the resource the first time, and then tell the client how to cache the resource based on the information returned, whether it’s a strong cache or a negotiated cache, depending on the header content of the response.

In the response header, there are four fields related to the cache. Strong cache: No request is made.

  • Cache-control: max-age=number(in seconds), which specifies an expiration time, as specified in the HTTP1.1 specification.
  • Expires, whose value is a time string in the GMT format of the time, old specification.

Negotiation cache: a request is made.

Both pairs are paired. The response header for the first request carries a field (last-Modified or Etag) and the subsequent request carries the corresponding request field (if-Modified-since or if-none-match). If the response header does not have a Last-Modified or Etag field, the request header does not have a corresponding field.

  • Etag, as the name suggests, will print a resource with a “QR code” and the request header if-none-match (If any), will not be re-requested and is responsible for returning 304. See MDN
  • Last-modified is also a time string in GMT format. In contrast to the request header if-modified-since (If any), 304 is returned unchanged

How do you clear a strong cache?

This is as simple as adding a query field to the URI, which we call the version number.

I’ll try using Node: config.js

module.export = {

cache: {

maxAge: 600,

cacheControl: true,

expires: true,

lastModified: true,

etag: true

}

}

Copy the code

catch.js

const conf = require('.. /config')

// stats is a file in the file server and can be ignored here

function refreshRes(stats, res) {

const {maxAge, expires, cacheControl, lastModified, etag} = conf.cache

if (expires) {

res.setHeader('Expires', (new Date(Date.now() + maxAge * 1000)).toUTCString())

}

if (cacheControl) {

res.setHeader('Cache-Control', `public, max-age=${maxAge}`)

}

if (lastModified) {

res.setHeader('Last-Modified', stats.mtime.toUTCString())

}

if (etag) {

const _et = new Date(stats.mtime).getTime()

res.setHeader('ETag', `${stats.size}-${_et}`)

}

}

module.exports = (stats, req, res) => {

refreshRes(stats, res)

const lastModified = req.headers['if-modified-since']

const etag = req.headers['if-none-match']

if (! lastModified && ! etag) {

return false

}

if (lastModified && lastModified ! == res.getHeader('Last-Modified')) {

return false

}

if (etag && etag ! == res.getHeader('Etage')) {

return false

}

return true

}

Copy the code

Here we sort out the content of the article:

  • The commonly used status codes are listed, 2xx, 3XX, 4XX, 5XX; In particular, 304 is related to caching. 401 will remind you that you need to intercept your request and add the token field in the request header.
  • Strong cache and negotiated cache; Strong caching corresponds to the response header:cache-controlThe units are seconds,expiresThe unit is time string; Negotiation cache: Etag/ if-none-match; Last-modified/If Modified – Since; The essence is to compare whether a resource is expired.The strong cache does not initiate the request, the negotiated cache does.
  • In conjunction with the previous article, we saw that HTTP request and response headers are very closely related to our development. To understand HTTP, in addition to understanding the commonly used HTTP status code, its request entity, response entity is an important part of our research, but also the part of our development. And, as we’ll see,responseThe response header field can be controlled, we can return different content for ourselves, and this is one of the things that the backend student development interface does.

Picture from Zhihu zhang Yunlong’s answer, highly recommended reading to be continued

Please leave me a comment on GitHub. Let’s learn and improve together.