Http

This article is a study note covering HTTP/1, HTTP/2, CSP, restful apis, cross-domain, and more.

How does the browser process from entering a URL to returning an HTTP response?

HTTP-1.0

Depend on other protocols

HTTP relies on other protocols, such as IP, TCP, UDP, DNS, and ARP

  • TCP/IP, layered protocol

    • Application layer: FTP, DNS, and HTTP
    • Transport layer: TCP and UDP
    • Network layer: The packet is the smallest unit of data transmitted over the network
    • Link layer: Handles the hardware part that connects the network
  • ARP converts IP addresses into MAC addresses

  • DNS protocol: Converts domain names to IP addresses

HTTP packets are transmitted through the preceding protocols. The transmission process is as follows:

In transit, there is an important concept, what is the TCP three-way handshake?

More broadly, how do protocols work together when a browser enters a URL?

There is another very important concept…

  • Urls are uniform resource locators, such ashttp://b.edu.51cto.com
  • Uri Uniform resource identifier, such asftp://abc/a.txt

The application of HTTP

HTTP is mainly used for communication between clients and servers and communication data forwarding services. The following are the communication data forwarding applications:

  • A proxy that accepts requests sent by the client and forwards them to the server, and receives responses from the server and forwards them to the client

  • The gateway receives the request from the client as if it had its own resources, and processes the request (forwards the data from other servers in the LAN, and the local area communication protocol may not be HTTP).

  • A tunnel, an application that transmits between clients and servers far apart and keeps both sides connected by communication

The meaning of proxy: caching proxy (caching server resources), transparent proxy (no processing of packets), and non-transparent proxy (processing of packet contents)

The significance of gateway: convert non-HTTP services into HTTP services to improve communication security?

Significance of tunnels: A tunnel can establish a communication line with other servers as required and use encryption methods such as SSL to communicate. The purpose of the tunnel is to ensure secure communication between the client and the server. The tunnel itself does not parse HTTP requests; requests and responses are transmitted as they are; The tunnel ends when the communication ends.

The cache is a copy of resources stored on the local disk of the proxy server or client. The cache can reduce the access to the source server, thus saving traffic and time. The cache can be set to expire and re-requested if the resource expires.

HTTP features and pitfalls

  • stateless

Do not save the communication state (such as login state) between the request and response, do not do persistent processing, the benefit is simple!

  • There is no connection

The advantage of disconnecting the TCP connection after the request is completed is that the server consumes less CPU and memory

As the Web became more complex and users expected better experiences, such as faster speeds, retention of logins, and so on, improvements were needed.

How to preserve the user’s state (such as login state), hence the Cookie technology:

The TCP connection process is quite complex and requires three handshakes to transfer data. Could you save handshake time, hence persistent connection technology:

HTTP/1.1 began to support persistent connections, which are persistent by default. Persistent connections use fields: connection:keep-alive; To speed things up even further, Chrome opens up to six threads for a single domain to request resources.

Traditional HTTP is a request/response model, in which a single request must wait for a response to complete before any other request can proceed. How to save the request wait time, hence the piping technique:

Pipelinization overcomes the blocking of concurrent request constraints in the same domain by sending all requests together to the server, which responds sequentially (relying on persistent connection technology).

The HTTP message

To learn HTTP, you must understand the packet. Through the packet structure, you can understand various additional information of the request/response, such as:

  • Entity type, request data type multipart/form-data, application/ JSON

  • Range request for partial content (breakpoint recovery download), Range: bytes=5001-10000

  • Content negotiation: The client and the server negotiate with each other on the resource Content of the response, and then provide the client with the most suitable resource, such as Accept, accept-Charset, Accept-Encoding, Accept-Language, and Content-language

  • Cache Control information, such as cache-Control, Expires

HTTP request packet

HTTP response packet

HTTP packet Structure

The HTTP request method: get/post/put/delete/head/option/trace/connect

Post and Get are commonly used in business. What is the difference between them?

2. The URL of the GET request can be bookmarks, but the URL of the POST request cannot be bookmarks. 4. Get only supports URI encoding, while POST supports multiple encoding forms. 5. The parameters in POST are not reserved. 6. The length of data carried in a GET request is limited, while that in POST is not limited. Post, on the other hand, uses the request BodyCopy the code

HTTP status code:

204, the request is successfully processed by the server, but the response packet does not contain the entity body part. 204 response is received, and the browser page is not updated. 206, the client makes a Range request, and the server successfully processes it and returns the entity Content in the specified content-Range. 301, a permanent redirect. The requested resource is assigned to a new URI, and the URI to which the resource now refers should be used later. If the bookmark is saved, it will be redirected when opened (the browser remembers the redirect address). Res.location + res.sendStatus with res.redirect equivalent to res.redirect: 302, temporary redirect, where the requested resource is assigned to a new URI and the user is expected to use the new URI this time. If the request meets the condition, the request will return 304. If the request meets the condition, the request will be allowed to access 307. ? 400: Syntax errors exist in the request packet. Modify the request content and send the request again. Will browsers treat the status code like 200? (how to deal with 200?) 401: The request needs to pass HTTP authentication (BASIC authentication, DIGEST authentication). If the request is returned with the authentication information, the authentication fails 403. 404 The requested resource is rejected by the server. 503. The server is under overload or is down for maintenance and cannot process requestsCopy the code

HTTP header field:

Header fields are classified by type or cache behavior:

Gm’s first field, request header fields, the first response, entity first field First field according to the caching behavior is divided into two types, the end-to-end first field (final goal of receiving of request and response), jump line by the first field (due to by caching or proxy server is no longer forward, after the HTTP / 1.1 must cooperate with the connection to use!)

# client request headerGET/HTTP/1.1 Upgrade: HTTP/1.1 Connection: UpgradeThe header sent to the Web server after passing through the proxy server
GET / HTTP/1.1
Copy the code

Generic header field

Request header field

Response header field

Entity head field

Hop – by – hop header field

General header field

  • Cache-control: controls the Cache logic

    • Public, the response can be cached by any object (proxy server, client)
    • Private, the response can only be cached by the client that initiated the request, not as a shared cache (proxy server)
    • No-cache: the cache resource must be validated each time before it can be used
    • No-store does not cache anything
    • No-transform, resources cannot be converted or transformed. HTTP headers such as content-encoding, content-range, and Content-Type cannot be modified by the proxy
    • Max-age: sets the maximum period for cache storage
    • S-maxage, cache server usage, cache time
    • Max-stale, initiates a request to carry, even if the cache expires, the cache can still be used for statle time
    • Must -revalidate, when the cache max-age expires, a new resource must be obtained from the server
    • Proxy-revalidate, used by the cache server, has the same effect as above
  • Connection: Manages persistent links, used in conjunction with a hop-by-hop header field

    • Close: indicates that the client or server wants to close the network connection
    • Keep-alive indicates that the client wants to keep the network persistent
  • Pragma: no longer recommended, basically the same as cache-control

  • Date: indicates the Date and event when a packet is created

  • Trailer: Waiting for query

  • Transfer-encoding: Hop – by – hop message header, used to specify the encoding form

    • chunked
    • compress
    • deflate
    • gzip
    • identity
  • Upgrade: asks the server whether to support other protocols, or HTTP higher protocol? Need to be used with connection?

  • Via: Tracing the transmission path of request response packets between the client and server to avoid repeated requests

  • Warning: Indicates that a packet has a problem. Some warning codes can only be used to cache response packets from the proxy server

Description of the request header field

Sent from the client to supplement the request with additional information, client information, priority related to the response content, etc

  • Accept tells the server what media types the user (or agent) can handle and their relative priority, such as Accept: text/plain; 1 = 0.3, text/HTML

  • Accept-charset informs the server of the character set supported by the user (or agent) and the relative priority of the character set, such as accept-charset: UTF-8, ISO-8859-1. Q = 0.5

    The content-type response field returns the server selection, for example, content-type: text/ HTML. charset=utf-8

  • Accept-encoding, which tells the server the content Encoding supported by the user (or agent) and the priority of the content Encoding. For example, accept-encoding: gzip, COMPRESS, Deflate, identity

    Content-encoding The response field returns the server selection, such as Content-Encoding: gzip

  • Accept-language, which tells the server the set of natural languages (Chinese or English) that the user agent can process. If the Accept – Language: en – US, en. Q = 0.5

    Content-language The response field returns the server selection, such as Content-language: de-de

  • Authorization: informs the server of the credentials used to authenticate users, for example, Authorization: Basic ABCDEFG

  • Expect: The server can handle requests properly only if this expected condition is met. Expect: 100-continue(client sends a large message body) and wait for a status code of 100 before sending the message body?

  • Form, email

  • Host, virtual hosts run on the same IP address. Use this field to distinguish them

  • If-match: conditional request. After the server accepts a conditional request, it performs the request only If the request is true. (if-match, same resource ETag value)

  • If-modified-since, resource update time ;;;; Returns the status code 304Not Modified if the resource is not updated

  • If-none-match, the opposite of if-match

  • If-range, If the field value matches the Etag or update date, continues as a Range request. Used with the Range field. If not, all resources are returned. (Save request times??)

  • Max-forwards sets the number of requests forwarded by the proxy server.

  • proxy-Authorization

  • Range: bytes=5001-10000 (206 is returned on success; 200+ all resources are returned on failure)

  • Referer, which tells the server the URI of the original resource requested, is often used to prevent theft.

  • TE, which tells the server which transmission Encoding the client can respond to and the relative priority, similar to the accept-encoding function.

  • UserAgent: passes information such as the name of the browser and userAgent that created the request to the server.

Response header field

Additional information to supplement the response, server information, and additional requirements for the client.

  • Accept-ranges: bytes can handle range requests, None cannot

  • Age, how long ago the response was created by the source server, with a field value of seconds. ?????

  • Etag, entity identifier, URI the same, using Etag to distinguish files

    • Strong Etag, which changes its value no matter how subtle an entity changes. If the Etag: usagi – 1234
    • Weak Etag, used to indicate whether the resources are the same. The ETag value is changed only when the resource is fundamentally changed, resulting in a difference.
  • Location directs the response recipient to a resource at a different Location from the request URI, basically in coordination with 3XX:Redirection.

  • The Proxy – Authenticate,

  • Retry-after, which tells you how long it will take the client to send the request again. With the status code 503Service Unavailable. Or 3XX Redirect. You can specify a specific date or the number of seconds after the response was created

  • Server: tells the client about the HTTP service program installed on the Server, for example, Server: Apache/2.2.6(Unix) PHP/5.2.5

  • vary

  • www-Authenticate

Entity header fields in detail

Header used in the entity part of the request message and response message. It is used to supplement the information related to the entity, such as the update time of the content

  • Allow, GET/HEAD, notifies the client that only specified methods are accepted
  • Content-encoding: End-to-end header field (similar to Transfer-Encoding), entity Content Encoding.
  • Content-language: zh-cn, notifying the client of the natural Language used by the entity (Chinese or English)
  • Content-length: specifies the size of the body of the entity
  • The Content – the Location,
  • Content-md5: The packet body generates MD5 codes. The server uses the same algorithm to calculate and compare packets. (But it is not aware whether the message body is tampered with ????) Is it used to determine the validity of the packet body?
  • Content-range, used in response to a Range request to specify the Range of the entity
  • Content-type, the media Type of the object in the entity body, e.gtext/html; application/x-www-form-urlencoded
  • Exprires, which specifies the expiration date of the resource. (If both fields are max-age, the max-age field is preferentially processed.)
  • Last-modified: specifies when the resource was last Modified.

Cookie field details

Set-cookie: indicates that the server sends a cookie. Set-cookie: status=enable; expires=Tue, 05 Jul 2011 07:26:31 GMT path=/ domain=.hack.jp secure httponly

  • Expires, max-age Specifies the cookie validity period
  • Path specifies the range of cookies
  • Domain Specified domain name
  • Secure Indicates that cookies are sent only for HTTPS links
  • Httponly specifies that JS cannot obtain cookies
  • Cookies. The server automatically carries cookies when requested
  • After closing the browser, cookies with no set time will be automatically cleared.

HTTP Authentication Mechanism

Authentication information usually includes: password, dynamic token, digital certificate, biometric authentication, IC card. How does HTTP authenticate?

HTTP uses forms to carry passwords for authentication, and manages status by means of cookies, session, JWT, etc. The specific process is as follows:

Note: How does the server save the password securely? The password is salted to add extra information, processed using a hash function, and finally the hash value is stored!

  • Cookie technology

Stored in the client, the server mainly delivers set-cookies. Cookies comply with the same origin policy and are carried automatically with each request. Cookies have a size limit of 3KB per cookie.

  • session

It is stored on the server to record user status. Relies on cookie technology (delivering session cookies). A large number of visitors occupies the server performance.

  • JWT

Session-cookie technology: It is safe for a session to be stored on the server and can be manually cleared, ensuring good compatibility. However, it is not friendly in a cross-domain scenario, and cookie-based techniques can easily be CRSF (cross-site request forgery).

JWT technology, the server will encrypt the information (and set the check) and send it to the client. The client is stored in sessionStorage or localStorage. The Authorization field in each request carries THE JWT information, and the server will return the information after passing the verification.

HTTPS security

Understand network security:

  • Network information security and confidentiality of three elements: confidentiality, integrity, availability
  • Symmetric encryption: Use the same key for encryption and decryption
  • Asymmetric encryption: Encryption and decryption using a unique pair of keys (public and private). Public key encryption and private key decryption are called decryption; Private key encryption and public key decryption are called signature and verification signature. (RSA, DSA)
  • Unidirectional encryption: irreversible encryption, fixed-length output. (MD5, SHA1, sha256)

The disadvantage of HTTP

  • Communication uses plaintext and the content may be monitored.
  • If the identity of the communication party is not verified, it may encounter camouflage attacks.
  • Packet integrity cannot be proved and may be tampered with.

HTTPS Encrypts HTTP traffic using SSL or TLS and implements identity authentication based on certificate services, that is, HTTP + encryption + authentication + integrity protection === HTTPS. However, encryption and decryption consume computing resources and slow down communication.

HTTPS Encryption Principle

Shared key encryption:

Public key encryption:

Hybrid encryption mechanism:

Importing a certificate to prove that the public key is correct:

Understand the principle of encryption and decryption, understand the principle of certificate, HTTPS to establish the whole process of communication:

AJAX technology such as

Traditional HTTP communication processes, which return the entire page on each request, cannot do local updates:

AJAX techniques, using JS to perform asynchronous network requests, can implement local updates:

Comet technology, after receiving the request, the server will wait for the content update, and then return the response, which implements the server push, but in order to maintain the link, it needs to consume more resources:

Polling efficiency is low, so there is a full duplex communication Websocket, its most common scenario – chat software

The front security

Understand the CSP/ Same-origin policy of the browser and common attack modes to ensure service security.

Main attack forms of front-end: XSS cross-site scripting attack, SQL injection, CSRF cross-site request forgery.

Content-Security-Policy

Content security policies used to attenuate and weaken certain types of attacks, including cross-site scripting and data injection attacks. CSP backward compatible, web pages are secure by default using the same origin policy.

How to use:

Defense Principles:

Specify the source of the browser’s executable JS to avoid XSS scripting attacks. Specify the resource loading domain; Specify the protocol for loading resources, such as mandatory HTTPS.

Common fields’ default-src/script-src/style-src/img-src/self

Cross-domain and same-origin policies

The same origin policy restricts how documents or scripts loaded from the same source can interact with resources from another source. The same origin is defined as the same protocol/domain name/port.

How to implement communication for requests that do not comply with the same origin policy? How do you cross domains?

–disable-web-security –user-data-dir=C:\MyChromeDevUserData –disable-web-security –user-data-dir=C:\MyChromeDevUserData www.cnblogs.com/laden666666…

In addition to the above hack methods, there are the following formal approaches.

CORS cross-domain resource sharing

Ajax complies with the same origin policy. How do you overcome the cross-domain limitations of Ajax? The CORS method!

  • Conditions for simple requests

    • The request methods can only be HEAD, GET, or POST
    • Header fields include: Accept, accept-language, content-language, content-type (application/x-www-form-urlencoded,multipart/form-data,text/plain)
  • Cors request process

    • The request carries the Origin field, indicating the source (protocol + domain name + port) from which the request is sent.
    • The response will contain fields such as access-Control-allow-Origin
  • Advance request

    • For non-simple requests, a pre-request is made before a formal request is made

    • Using the OPTIONS method, ask the browser whether to allow cross-source requests

      OPTIONS /cors HTTP/1.1
      Origin: http://api.bob.com
      Access-Control-Request-Method: PUT
      Access-Control-Request-Headers: X-Custom-Header
      Copy the code

Jsonp cross-domain requests

Cors is more powerful than JSONP and supports all request types; Jsonp only supports GET requests, but jSONP supports older browsers and is more compatible. The implementation code of JSOP is as follows:

function jsonp(src, onsuccess, onerror) {
    const callback = 'callback_' + Math.random().toString().substr(1.6)
    window[callback] = function () {
        onsuccess && onsuccess.apply(null.arguments)}const script = document.createElement('script')
    script.setAttribute("type"."text/javascript")
    script.setAttribute('src'.`${src}? jsonp=${callback}`)
    script.async = true
    script.onload = script.onreadstatechange = function () {
        if(! script.readystate &&/complete|loaded/.test(script.readystate)) {
            script.onload = script.onreadstatechange = null
            if (script.parentNode) {
                script.parentNode.removeChild(script)
            }
            window[callback] = null
        }
    }
    script.onerror = function () {
        onerror && onerror()
    }

    document.appendChild(script)
}
Copy the code

WebSocket

Webscoket full duplex communication, event-driven response, supports cross-domain communication.

/ / the client
let ws = new WebSocket('ws://localhost:3000/')
ws.onopen = function() {
    ws.send('Hello! ');
}
ws.onmessage = function(msg) {
    console.log('get Message:', msg.data); 
}

/ / the server
const WebSocket = require('ws')
const wss = new WebSocket.Server({port: 3000})
wss.on('connection'.function(ws) {
  ws.on('message'.function (message) {
    ws.send(`${message}-server`, err => {
      if (err) {
        console.log(err)
      }
    })
  })
})
Copy the code

XSS– Cross-site scripting attacks

The attack principle is shown in the figure below, with normal rendering in the figure above and attack mode in the figure below:

XSS scripts are extremely harmful, and embedding executable scripts can do a lot of things:

  • Get page data
  • To get the cookies
  • Hijack front-end logic
  • Send the request

XSS is divided into:

  • Reflection: URL parameters are directly injected
  • Storage type: store data to DB and then read and inject

XSS attack path:

  • Node content attack: template code<p v-html="from"></p>, attack payloadhttp://localhost:8080/?from=%3Cscript%3Ealert(1)%3C/script%3E
  • HTML attribute attack: template code<img src="avatar"/>, attack payloadhttp://localhost:8080/?avatar=1%22onerror=%22alert(1)%22
  • Rich text: Displays rich text content<p>hello world! </p><script>alert(1)</script>

How to effectively defend against the above attack modes?

  • Defense node content and properties: The browser provides XSS defenseX-XSS-Protection, for reflective XSS
  • Defense node content:<>Such special symbols are escaped into the entity character set
function SaferHTML(templateData) {
    let s = templateData[0];
    for (let i = 1; i < arguments.length; i++) {
      let arg = String(arguments[i]);
  
      // Escape special characters in the substitution.
      s += arg.replace(/&/g."&amp;")
              .replace(/</g."&lt;")
              .replace(/>/g."&gt;")
              .replace(/"/g."&quot;")
              .replace(/'/g.'& # 39; ')
              .replace(/ /g.'the & # 160; ');
  
      // Don't escape special characters in the template.
      s += templateData[i];
    }
    return s;
  }
Copy the code
  • Rich text defense: Blacklist filtering, filtering out onerror and other attributes. Whitelisting retains some of the tags and attributes defined[{img: ['src']}]

CSRF– Cross-site request forgery

The user logs in to website A and induces the user on website B to initiate A request to website A (Step 3). Due to the same origin policy, the attack request automatically carries A cookie.

Cross-site request forgery ** uses user login status to complete business requests *, and can steal user funds, impersonate users to post

How to effectively defend against the above attack features?

  • A Cookie is setsame-siteProperty, the same site only automatically carry cookies
  • Add authentication information, such as verification code and token, to the user front page<input name="csrf" value="xxx" hidden/>Form to verify the source of the request
  • Verify the referer address of the request and disallow requests from third party websites

Click on the hijacked

Website B uses iframe to embed website A and induce users to click on website A for interaction. The user doesn’t know it, but he does it himself.

How to protect against clickjacking?

  • Use JStop.location === window.location, forbid inline
  • Set x-frame-options to disable embedding
  • Verification code and other auxiliary means

Other security

HTTPS is used to address security issues such as HTTP transmission eavesdropping

Cookies are often used to retain login state. How to ensure Cookie security?

  • Set up thehttp-onlyJS is prohibited from operating on cookies
  • Set up thesame-siteAvoid cross-site request forgery

The password is used to prove that “you are you”. It is forbidden to store the password in plain text.

  • Password disclosure channel

    • The server is invaded.
    • Communications are being intercepted. HTTP intercepts
    • An insider leaks data
    • Hit library
  • The hash algorithm

    Use complex passwords against rainbow tables, md5(SHA1 (MD5 (id+ AB83KD + original password +81kdso+ salt + 1Lso; $2))) The more changes, the more complex and secure the password.

  • Transport security

    • HTTPS transport
    • Login frequency limit
    • Front-end encryption is of limited significance
  • Biometric code

    • Privacy – Easy to leak
    • Safety – Collision
    • Unique, lifetime unique, cannot be modified

And file upload security?

Avoid uploading files to be executed as programs!

HTTP2

Based on restful apis, HTTP/1.1 radically transforms HTTP from a document-oriented protocol to a resource-oriented one by introducing the concept of “resources.” The main impact of HTTP-2 is faster and more secure transport.

How is HTTP2 faster?

Analyze HTTP request response flow chart to find key performance indicators:

After analysis, the key performance indicators are as follows:

  • Network metrics: Latency, bandwidth, DNS query, connection establishment time (TCP three-way handshake), TLS negotiation time (HTTPS connection)

  • Server optimization: First byte time (TTFB, the browser from a request to accept the time between the first byte), content download time later arrival time (request resources TTLB), begin to render time (when to start the screen display content, namely the user sees the length of the blank page), document load completion time (browser think finished page load time)

  • Network trends: more bytes (web content grows), more resources (more resources referenced), higher complexity (web page rendering complexity), more domain names, more TCP links

HTTP/1 defects and optimizations

Defect:

  • Queue head blocking: For persistent connections, Chrome opens six connections for a single domain name and obtains resources in sequence. If the acquisition of a resource fails, network transmission and Web page rendering will be affected.
  • Inefficient TCP utilization: TCP starts slowly (congestion control) and requires multiple data exchanges to transfer the largest data packet. TCP ensures the normal operation of the connection, but does not guarantee the optimal performance.
  • Bloated message headers: There are too many resources and too many requests. Message headers are carried each time, consuming resources.
  • Restricted priority: HTTP/1 is primarily a request-response mechanism. Browsers request higher-priority resources first, while lower-priority resources wait for higher-priority requests to complete, wasting time in between.
  • You can select any data compression format but not mandatory compression mode
  • Uncontrollability: Delays blocking page rendering if problems occur with third-party resources.

Optimization:

  • DNS query optimization: limit the number of domain names (reasonable split domain names); DNS preresolution:<link rel="dns-prefetch" href="//ajax.googlepis.com">.
  • Optimizing TCP connections: preconnect directive:<link rel="preconnect" href="" crossorigin>.
  • Avoid redirects: Redirects can cause delays of hundreds of milliseconds, and requests are redirected in the cloud
  • Caching: use client-side caching (cache-control caching); CDN cache.
  • Compression: code compression (Spaces, etc.); Transmission compression gZIP, etc.
  • Prevent JS blocking pages: set async and defeer properties; Put in place.
  • Image optimization: image compression; Responsive picture

HTTP / 2 anti-patterns

Partial optimizations for HTTP/1 May be anti-optimizations under HTTP/2:

  • HTTP/2 requests are no longer blocking, multiple requests can be processed in parallel, and sprites are meaningless in terms of performance
  • There is no need for domain name splitting, HTTP/2 supports multiplexing (HTTP/1 enables 6 request processes for each domain name, reasonable splitting is conducive to more request capacity; But HTTP/2 only opens one connection, request multiplexing)
  • You do not need to set a separate domain name for images, saving DNS and TCP connection time. (HTTP/1 requests carry cookies. Therefore, static resources such as images use different domain names to avoid useless cookies. But in HTTP/2, headers are compressed, and both clients and servers retain the “header history” and no longer carry cookies each time they request an image.

This section describes the HTTP/2 protocol

HTTP/2 is designed for compatibility. Any client that does not support HTTP/2 simply reverts to HTTP/1. HTTP/2 generally means HTTPS, and port 443 is enabled by default.

The HTTP/2 protocol is roughly divided into two parts: the frame-breaking layer, or H2 multiplexing capability; The data layer, the HTTP data part. Main features: binary protocol, head compression, multiplexing, encrypted transmission.

  • Connection: Initializes a TCP connection over which frames and streams are transmitted

  • Frames: Request and response can be interleaved and even multiplexed, which helps to solve queue head congestion

  • Flow: An independent, bidirectional sequence exchange of frames over h2 links. The client initiates a request, which opens a stream on which the server replies. With framing, multiple requests and responses can be interleaved without blocking.

  • Message: A stream is used to transmit a pair of request/response messages, h2 messages containing HEADERS frames and DATA frames

  • Priority: H2 analyzes dependencies and requests the most important resources first

  • Server push: The best way to improve the performance of a single object is to put it in the browser’s cache before it is used

  • First compression: Hpack compression algorithm

What factors affect H2 performance?

H2 is designed to improve performance, but HTTP/2’s speed has its lifeblood:

  • Delay: H2 is affected by less growth than H1
  • Packet loss: The TCP congestion window fluctuates due to packet loss. H2 opens only one TCP connection, which greatly affects the TCP congestion window (packet loss is the lifeblood of H2).

RestfulApi

RestfulApi content from this article: imweb. IO /topic/57075…

The main point of the RestFulApi is to move HTTP from document-oriented to resource-oriented

1. Each URI represents a resource. 2. Between the client and the server, a representation layer of this resource is transmitted. (If the client wants to operate the server, it must make the server "state transition" by some means. Representational State Transfer-- RESTfulApi) 3. The client operates on the server resources through four HTTP verbs to achieve "state transformation of the realization layer"Copy the code
  • Status code

    • Using HTTP status codes (HTTP status codes pre-define error messages)
    • Custom, refer to wechat (0 indicates success, other error codes) : mp.weixin.qq.com/wiki?t=reso…
  • Interface requirements

    • Idempotent: For the same interface, using the same conditions, a single request and repeated multiple requests have the same impact on system resources.
    • Security: How to ensure interface security?
  • In actual combat

    • The version number is in the following format:http://api.example.com/v1/zoos
    • Operations: GET Obtain resources, POST create resources, PUT update resources (complete), DELETE DELETE resources, PATCH update resources

GraphQL

To be supplemented by learning.

The cache

Cache hit flowchart:

Resource tips and instructions

Browsers offer some new ways to load resources – resource hints and instructions:

  • Preload: Unlike browser preloading, preload can preload resources defined in CSS and JS and allow you to decide when to apply each resource; Preload does not block the window’s onload event.

    <link rel="preload">

  • Prefetch: A low-priority resource prompt that allows the browser to fetch resources in the background (when idle) that may be available in the future and store them in the browser cache.

    • <link rel="prefetch" href="pic.png">
    • <link re="dns-prefetch" href="//baidu.com">
  • Prerendering: Similar to Prefetch, prerendering renders the entire page in the background

  • Preconnect: The browser performs some actions before an HTTP request is formally sent to the server, including DNS resolution, TLS negotiation, and TCP handshake, which eliminates round-trip latency and saves the user time.

Resource tips and instructions

Ajax request types

The front and back ends use Ajax to transmit data and define the data format through content-Type. The common methods are as follows:

  1. application/x-www-form-urlencoded

The default encoding form of the element label form. The data needs to be transferred into the form of name= JJ&age =17. The third-party library QS is recommended for data processing.

// application/www-form-urlencode
function ajaxBy1 () {
    let xhr = new XMLHttpRequest()
    xhr.open('POST'.'http://localhost')
    xhr.setRequestHeader('Content-type'.'application/x-www-form-urlencoded')
    xhr.send('name=jj&age=17')}Copy the code
  1. application/form-data

The element tag form can modify encType =application/form-data or create a FormData instance object with new FormData(). This scheme also supports file uploads.

// multipart/form-data
function ajaxBy2 () {
    const data = new FormData()
    data.append('name'.'jj')
    data.append('age'18),let xhr = new XMLHttpRequest()
    xhr.open('POST'.'http://localhost')
    xhr.send(data)
}
Copy the code
  1. application/json

If the data structure is complex, you are advised to use Application/JSON to directly transfer JSON objects.

// application/json
function ajaxBy3 () {
    const data = {
        "name": "jj"."age": 18
    }
    let xhr = new XMLHttpRequest()
    xhr.open('POST'.'http://localhost:5501')
    xhr.setRequestHeader("Content-type"."application/json")
    xhr.send(JSON.stringify(data))
}

/ / breakpoint continuingly https://cloud.tencent.com/developer/article/1326932
Copy the code

What if you use a library such as AXIos for requests in your business?

recommended

Most of this article comes from the following sources and is recommended reading. Do not know whether the screenshot infringement, if there is infringement contact delete.

  1. Book: Illustrated HTTP
  2. Analysis and Defense of Web Front-end and back-end vulnerabilities