Computer network knowledge frequently asked in front-end interviews

Computer network knowledge frequently asked in front-end interviews

This article has participated in the Haowen Convening Order activity, click to view: Back-end, big front-end dual track submissions, 20,000 yuan prize pool waiting for your challenge!

OSI and TCP/IP model

What happened to the address

Hypothetical input

The browser resolves the domain name.

When the client and the server exchange data, the domain name cannot be recognized, and the unused IP address is converted through DNS resolution of the domain name

  • Look up whether there is a mapping relationship in the browser cache
  • Query the local host file to see if there is a correspondence between the domain name and the ip, if any, parse the ip directly
  • If the host file does not exist, go to the local DNS server (the dns provided by China Mobile Unicom telecom operator) to find out if there is a mapping relationship between the IP and the domain name. If so, return
  • If you haven't found it, go to the root server to find it
  • The root server will determine who manages this domain name, here
    Be responsible
    The top-level domain name server management, and then return the ip of this server. Top-level domain name server (gTLD Server): .com, .cn and other domain names
  • The dns server in this area will continue to query the ip of this top-level domain name server, and he will return the domain name server corresponding to the domain name. This domain name server is the domain name server you registered, and the server of this domain name service provider will take on the task of domain name resolution.
  • The domain name server returns the resolved ip to the server in the region
  • The local server caches the resolution result
  • Return the parsed result to the user

TCP/IP three-way handshake to establish a connection

A question arises: why is it three times? What's the problem with establishing the connection twice? 4.times

  • In the first handshake, the client's TCP sends a connection request message to the server's TCP.
    (SYN stands for initiating a new connection), and a random start signal
    (seq signal, 32 bits, used to identify the byte stream sent from the TCP source to the destination, and the initiator will mark this when sending data)
  • In the second handshake, after the server TCP receives the request message, it sends a request to the client, and allocates TCP buffers and variables for the TCP connection. It sends four fields to the client:
    (Confirm that the signal is valid)
    (ack serial number, 32 bits, only when the ACK flag position is 1, ack is valid, ack=seq+1), randomly generated one
  • When the client receives the confirmed message, it needs to continue to confirm to the server, and also allocate cache and variables to the link

Description of several states:

  • CLOSED: The connection is over, there is no connection status
  • LISTEN: monitor the remote connection, you can receive the connection
  • SYN_SENT: When the client connects, it enters the SYN_SENT state after sending SYN
  • SYN_REVD: The server received the SYN message sent by the client
  • ESTABLISHED: Identifies that the TCP connection has been successfully established

The browser client sends data to the backend

  • After the three-way handshake establishes a connection, send a request to the background

Back-end data is returned to the browser for rendering

  • Parse the html structure, build the dom tree, then parse out all the tags

  • Build the cssom tree and parse the css style

  • Execute the code in the script tag (so avoid putting the tag in the head, causing page blanks and blocking)

    • Normal label: resolve to
      After the tag, load the script content, then execute it, and continue to parse the html after the execution is complete
    • defer: resolve to
      After that, there is no blocking, while parsing the html, loading the script again, and after all parsing with html is completed, execute the script
    • async: Similar to defer, except that the timing of the script execution is different. It does not block when loading the script. After the script is loaded, the script is executed.

  • Combine dom and cssom into a render tree

  • Draw the page according to the render tree

Wave four times to disconnect

Asks a question: Is it OK to wave three times?

  • Waved for the first time, the client sends a **connection release message,** and stops sending data again, and actively closes the TCP connection .
    (Release a connection),
  • The second wave: The server sends a confirmation after receiving the connection release message.
    At this point, the connection from the client to the server is released, and the TCP connection is half-closed . But if the server sends data, the client still has to receive it, that is, the connection from the server to the client is still not closed.
  • Wave for the third time: If the server has no data to send to the client, it informs TCP to release the connection , and at this time it sends a connection release message with FIN=1
  • Step 4: After the client receives the connection release message, it must send an acknowledgment. In the acknowledgment message, the ACK field is set to 1 , the confirmation number ack=w+1, and the sequence number seq=u+1. At this time, TCP The connection has not been released , the client must enter the connection closed state after the time 2MSL (MSL: the maximum survival time of the message) set by the waiting timer has elapsed .

Several states have to be explained:

  • FIN_WAIT_1 The client enters this state after sending a request to close the connection with FIN=1

  • CLOSE_WAIT: After receiving the request from the client to close the connection, the server confirms that the signal is valid, and enters after responding to the client

  • FIN_WAIT_2: The client enters after receiving the ACK from the server. Enter the semi-closed state, only the client can only receive data, not send data

  • LAST_ACK: The server sends a FIN close signal to the client, waiting for the other party to confirm

  • TIME_WAIT: The client enters after receiving the FIN close signal sent by the server, and waits for enough time 2MSL to ensure that the client receives an ACK confirming to close the connection

  • CLOSED: connection ended

TCP and UDP protocol

  • UDP protocol: The full name of the UDP protocol is the User Datagram Protocol. It is used to process data packets in the network like the TCP protocol and is a connectionless protocol.
  • TCP protocol: The full name of TCP protocol is Transmission Control Protocol, which is a connection-oriented, reliable, byte stream-based transport layer communication protocol. T
Whether to connectNo connection, don t care if the other party receives itConnection-oriented, it is necessary to ensure that both parties establish the correct connection
Is it reliableUnreliable transmission, without using flow control and congestion controlReliable transmission, using flow control and congestion control
Number of connected objectsSupport one-to-one, one-to-many, many-to-one and many-to-many interactive communicationCan only be one-to-one communication
Head overheadHeader overhead is small, only 8 bytesThe minimum header is 20 bytes, and the maximum is 60 bytes
Applicable sceneSuitable for real-time applications (IP telephony, video conferencing, live broadcast, etc.), with fast speed requirementsSuitable for applications that require reliable transmission, such as file transmission


Stateless, a protocol that runs in a request/response manner. It uses extensible semantics and self-describing message formats to interact flexibly with network-based hypertext information systems (html pages)

  • Stateless: Will not store user information
  • Request/response: send request ===> get corresponding
  • Extensible: Some fields can be added to the request header based on the protocol
  • Self-describing: can transfer text, pictures and other formats

Request type

  • get: The parameter is mounted on the url and is only used to obtain data

  • post: Submit the entity to the specified resource, focusing on adding data

  • put: focus on modifying the data, update the whole

  • patch: an additional supplement to the put method, used for partial updates

  • delete: delete the specified resource

  • head: the same as get, but only the response header is returned without the response body

  • options: preflight request, check which http methods the server supports, the response body contains one

    Field, contains the supported methods

  • connect: Create a two-way communication tunnel between the client and the requested resource, point-to-point communication

  • trace: The server returns the received information as it is, and provides a debug method

RESTful request style

Refer to the REStful API design guide of Ruan Yifeng

RESTful is resource-oriented. No verbs can exist in the URL, only nouns. code

For specific resource operations, HTTP provides the above request types. These verbs can be used to indicate which operations are performed on the resource. For some parameters, such as: get Tom's math score, write it with a get request, the request address is

, But written in RESTful style is
,List some common examples:

//Method Interface Behavior GET/zoos: List all zoos POST/zoos: Create a new zoo GET/zoos/ID: Get information about a specified zoo PUT/zoos/ID: Update the information of a specified zoo (provide all the information of the zoo) PATCH/zoos/ID: Update the information of a specified zoo (provide partial information of the zoo) DELETE/zoos/ID: delete a zoo GET/zoos/ID/animals: List all animals in a specified zoo DELETE/zoos/ID/animals/ID: Delete a specified animal in a specified zoo Copy code

Alias of these request methods are also provided in axios

axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config])[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) Copy code

Request header

  • Accept Browser Acceptable Data Format

  • Accept-Encoding The compression algorithm that the browser can accept, such as gzip

  • Accept-lanuage Languages that the browser can accept

  • Connection: keep-alive one TCP connection reuse (one connection, multiple use)

  • Cookies will be included in non-cross-domain requests

  • Host requested domain name

  • User-Agent (UA for short) requesting client and browser information

  • Content-type The format of the sender's data, such as application/json

    • application/json: converted into json string form
    • multipart/form-data: post transfer files
    • application/x-www-form-urlencoded: The default format of the form, the browser uses the x-www-form-urlencoded encoding method to convert the form data into a string (name1=value1&name2=value2) and then append this string to the url Later, split with? To load this new url. When the action is post, the browser encapsulates the form data in the http body, and then sends it to the server.


  • On the basis of HTTP protocol communication, a security protocol that uses SSL/TLS to provide security and data integrity for network communication to encrypt network connections


Refer to WebSocket related knowledge

Cross-domain issues

the reason

  • Same-origin policy: If the protocol, domain name, and port number are the same, it is called the same-origin. In order to ensure the security of information, the following behaviors will be restricted in the case of different sources:
    • cookie, localStorage, indexDB cannot be read
    • Unable to get DOM
    • The requested response is intercepted by the browser



Tags are not affected by the same-origin policy. The essence of jsonp is dynamically created
Tag, use the feature that it does not generate cross-domain, send a request to the background

  • The front end first declares a callback function sayName` after the request is successful
  • Front end creation
    Label, after receiving the request in the background, it returns a function name through some processing, and puts the data as a parameter, and returns
  • After the request is successful, the data will be put in and executed

The request sent to load the resource is a get request, so that jsonp also has this limitation.

node middleware agent

The same-origin policy is only a restriction of the browser, and does not restrict the mutual requests between servers

For example, here, the front end needs to

Request data. project
npm run dev
When running, a service 4000 is started locally. When the front-end sends a request, it will go through 4000. Then he sends a request to 5000. The forwarding request from 4000 to 5000 does not involve cross-domain. After the request is successful, 5000 returns a response to 4000, and then 4000 then forwarded to the front end

  • When using Vue to develop a project, it is inevitable to encounter cross-domain problems, usually to configure the scaffold
    (According to the scaffolding version), here is the use of middleware to start a service locally, all requests are sent to the locally created service, and then forwarded to the background by him

  • React cross-domain problems can also be solved by this method.


The key realization of cross-domain resource sharing lies in the server.

  • Access-COntrol-Allow-Origin
    : The key attribute, or when requested
    The value of the field, or a
    , Which means accepting requests for any domain name.
  • Access-Control-Allow-Credentials
    :The default is
    , Indicating whether the request carries credentials (representing cookies, authorization headers or TLS client certificates). Credentials must be configured on both front and back ends (ie, backend
    It must be configured in the front-end XHR or Fetch request) to make the CORS request with credentials succeed. If you decide to send a cookie, then
    Attribute cannot be set to
    , Must specify the required domain name consistent with the request
  • Access-Control-Expose-Headers
    : Appears in the response header, the exposed response header for the getResponseHeader() of the XMLHttpRequest object to obtain additional header information
  • Access-Control-Allow-Methods
    : Appears in the response to the preflight request, indicating that the server supports cross-domain methods
  • Access-Control-Allow-Headers
    : Appears in the response to the preflight request, indicating all the header information supported by the server, if the request header is set
    , Then this field is required.
  • Access-Control-Max-Age
    : Appears in the response header of the preflight request, indicating the validity period of the preflight request, in seconds, during which time the preflight request will not be sent
  • Access-Control-Request-Method
    : Required. It appears in the request header of the preflight request, indicating that the request method will actually be used for the real request
  • Access-Control-Request-Header
    : Appears in the request header of the preflight request, indicating which request headers the server will use in the real request

Nginx reverse proxy

Forward and reverse proxy

Configure nginx


Browser access

When, forwarded to

server { #Accessed port number listen 81 ; #Accessed address server_name localhost; location/{ root html; index index.html index.htm; # forwarded address proxy_pass; } } Copy code

HTTP cache

Refer to the article to understand http caching

When requesting data from the server, the browser cache will be queried first. If there is data that needs to be requested in the cache, the data will be directly extracted from the browser cache. The common http cache can only cache the resources that are requested by the get request.

  • http cache classification: according to whether to re-initiate a request to the server to classify, can be divided into strong cache and negotiation cache

  • http caching process:

    • Step 1: The browser requests data for the first time, and the server returns the resource, adding the resource's cache parameter in the response header .
    • Step 2: Determine the requested data and check whether it hits the strong cache. If it hits, the status code 200 will be returned, and the resource will be obtained from the browser, and the request will not be sent to the server.
    • Step 3: If the strong cache is missed, a request is sent to the server. The server will compare whether the cache is invalid and updated. If the resource is updated, it will return a status code of 200, get the resource from the server, and update the cache . Update, return the status code 304, and then go to the browser to get the resource

Forced caching

Force the cache when the cache has not expired, ie

The max-age attribute of Cache-Control
If it is not expired, it will go back to the browser's cache. When the forced cache takes effect, the http status code is 200. This method is the fastest page loading speed because it has not interacted with the server. But if the resources on the server are modified, the cache obtained at this time is not the data we expected, and the page is refreshed but it does not take effect. Because it is forced to cache, it will be fine after Ctrl + F5. . The header attributes related to forced caching are (Pragma/Cache-Control/Expires)

Related attributes:

  • Cache-Control
    • no-store
      : Prohibit any caching policy, the server must respond to a new resource when requested
    • no-cache
      Do not use strong cache, go directly to use negotiation cache, and
      Mutually exclusive, when set at the same time, subject to `no-store
    • max-age
      : Represents a relative length of time, relative to the client time, the unit is seconds, for example
      , Which means that it will expire after 31536000 seconds of a successful request, and each successful request will delay the invalidation time
    • s-maxage
      : Proxy server cache valid time,
      Valid under circumstances
    • private
      : Default value, can only be cached by the browser
    • public
      : Can be cached by the browser or by the proxy server,
  • Expires sets a fixed time at which the cache expires,
    Expires:Mon, 20 Jul 2017 10:08:35 GMT
    , Is valid before this moment, the request is successful will not delay the expiration time, under normal circumstances it is used

Negotiation cache

When there is no Cache-Control and Expires in the response header or Cache-Control and Expires expired or its attribute is set to no-cache (that is, the cache is not strengthened), then the browser will negotiate with the server for the second request (through judgment

Is last-modified/if-modified-since consistent
Is Etag/If-None-Match the same?
), compare with the server to determine whether the resource has been modified and updated. If the server resource has not changed, return 304. Then get the resource from the browser, if it has changed, get the resource from the server, return 200

Two ways to achieve negotiation caching:

  • Last-modified
    : Exists in the response header and identifies the last modification time of the file
  • If-modified-Since
    : Exists in the request header, the value is returned before

The above set of attributes can solve most caching situations, but there are some shortcomings. Their timestamp unit is seconds. That is to say, if the resource is modified too fast, it will be completed within a few hundred milliseconds. Are equal, it is not possible to recognize that the resource has been updated. In addition, there may be a situation where only the file name is changed without changing the file content. This situation will be regarded as a resource update, and will go to the service to request resources and consume performance. For the shortcomings of both, you can use

Plan optimization

  • Etag
    : The hash value that exists in the file is unique, and resource changes will change its Etag
  • If-None-Match
    : Exists in the request header, the value is returned before

Comparing the above two negotiation caching schemes, they all have a common process. The first time the server is requested to return an identifier and put in the response header, the second and subsequent requests will put the value of the response header in the request header. Compare two values to determine whether the resource has changed

This scheme is not a complete replacement

, He can only be used as a supplement, because it also has some shortcomings. First of all, the hash value of the file needs to be calculated by the server, which causes additional overhead to the server, especially for some large files or the case of a large number of files, frequent calculations The file hash value causes a loss of performance. In addition, there are accuracy problems in the process of generating etag, and some situations will cause the comparison to fail.


  • Cache decision process:

  • Different types of file caching schemes:

    The specific caching scheme needs to be determined according to the actual development scenario

    • The html file needs to be updated in time and needs to be set as a negotiation cache
    • Media files such as image files are large and may be replaced and changed regularly, and a shorter period of mandatory caching can be set
    • css style files, js script files can be set for a long time strong cache
  • Refresh the page behavior

    • F5 Refreshing the page will still find the strong cache of the browser and then go to the negotiation cache
    • Ctrl+F5 forced refresh
      Will become
      Do not strengthen the cache

Browser storage solution

Use of cookie, localStorage, sessionStorage



Cross-site scripting attacks, inserting scripts into the client, the user opens a webpage or clicks a button to run the injected script

Refer to the Meituan technical team: How to prevent XSS attacks

Injected scenario

  • In the text embedded in HTML, malicious content is injected with script tags. When rendering text, the data returned in the background contains
< H1 of > distal rendering data returned back: < Script > ALRT (. 1) </Script > </h1 of > copy the code
  • In inline JavaScript, the spliced data breaks through the original limitations (strings, variables, method names, etc.).
< Script > the let backendData ALRT = ( . 1 ) //backend data the let Data = backendData //distal these data operations Console .log (Data) </Script > copy the code
  • In the tag attribute, the malicious content contains quotation marks, thereby breaking the restriction of attribute value and injecting other attributes or tags.
Data returned from the background "> < script > alrt( 'XSS' ); </script > < input type = "text" value = "<%= getParameter(" keyword ") %> "> After splicing: < input type = "text" value = "" > < script > alrt( 'XSS' ); </script > "> Copy code
  • In the href, src and other attributes of the tag, include
    And other executable code.
Background returned data: JavaScript: ALRT ( 'XSS') < A the href = "<% = escapeHTML (the getParameter (" the redirect_to "))%> "> Go ... </A > After stitching < A the href = "JavaScript: ALRT ( 'XSS')" > Go ... </A > copy the code
  • Inject uncontrolled code in events such as onload, onerror, and onclick.
  • In the style attribute and tags, include similar
    The code (the new version of the browser has been able to prevent).
  • In the style attribute and tags, include similar
    CSS expression code (the new version of the browser can already prevent).

XSS classification

According to the source of the attack, XSS attacks can be divided into three types: storage type, reflection type and DOM type. For the first two types, the back-end should be protected, while the third DOM type needs front-end protection

  • Storage type: Submit malicious code to the database. When the user opens the page, the data is retrieved from the background, and then the data is spliced. The code will be executed when the browser renders the page. It is common in scenarios such as comments, private messages, and published articles.
  • Reflective: A special URL is constructed. When the user clicks to redirect to this URL, the malicious code is also parsed and executed. Commonly used in functions that pass parameters through URLs, such as website search, jump, etc. The difference from the storage type is that the malicious code of the stored XSS is stored in the database, and the malicious code of the reflective XSS is stored in the URL .
  • DOM type: the attacker constructs a special URL, the user opens the URL with malicious code, the malicious code steals user data and sends it to the attacker s website, or pretends to be the user s behavior, calling the target website interface to perform the attacker s specified operation

How to prevent

For storage type and reflective

They all take out malicious code from the background, and then spliced it in html, which is executed by the browser. There are two ways to prevent it:

  • Change to pure front-end rendering to separate code and data. This is commonly used in many internal and management systems

    1. The browser first loads a static HTML, which does not contain any business-related data.
    2. Then the browser executes the JavaScript in the HTML.
    3. JavaScript loads business data through Ajax and calls DOM API to update it on the page. Explicitly tell the browser: the content to be set below is text (
      ), or attribute (
      ), or style (
      )and many more. The browser will not be easily deceived and execute unexpected code
  • Fully escape the HTML. Use appropriate escape libraries, such as doT.js, ejs, FreeMarker, etc., to fully escape the insertion points of the HTML template. Put some key characters such as

    & <> "'/
    If it is escaped, the encoding of HTML is very complicated. Corresponding escape rules should be used in different contexts.

For DOM type

  • DOM type is because the page treats untrusted data as code execution, so it is using
    Be careful not to insert untrusted data on the page as HTML, but use it as much as possible
    Wait, for Vue/React technology stack, try not to use
    Function, avoid in the front-end render stage
    The hidden danger of XSS. Inline event listeners in the DOM, such as
    Attribute, JavaScript
    And so on, can run the string as code. If untrusted data is spliced into a string and passed to these APIs, it is easy to cause security risks.

Other preventive measures

  • Limit the length of the input content to be submitted
  • Set the http-only attribute to the cookie to prohibit the front-end browser from reading the cookie
  • Verification Code: Prevent the script from pretending to be a user to submit dangerous operations


Reference US Mission technical team how to prevent CSRF attacks

Cross-site request forgery, leading users to a third-party website, and then sending a request, impersonating the user's identity, and performing certain operations on the attacked website,

Common types of attacks

  • GET request type. After entering a third-party website, the browser requests image resources, and then sends a request to the attacked website
//Get the user cookie from bank.example < img style = "width:0;" src = "http://bank.example/withdraw?amount=10000&for=hacker" > Copy code
  • POST request, enter the third distribution website to automatically submit the form to send a post request
< form method = "POST" action = "https://bank.example/xxx" enctype = "multipart/form-data" > < input type = "hidden" name = "name" value = "xiaoming"/> < input type = "hidden" name = "amount" value = "10000"/> </form > < script > document .forms[ 0 ].submit(); </script > copy code
  • Jump links, induce users to click on links on the page, and forge requests in the link
< A href = "HTTP://bank.example/withdraw for AMOUNT = = 10000 & Hacker?" Taget = "_blank" > heavy news! ! < A/> copy the code

How to prevent

CSRF is just fraudulent use of cookies, and the actual value of cookies cannot be obtained. In addition, CSRF usually occurs on third-party websites

Homology detection

  • Origin (only protocol, domain name, port number. Does not contain detailed information about the path) or Referer (protocol, domain name, port number, parameters. The detailed address of the page source). Contains the source information of the request, you can determine the source of the request, and it is forbidden to exclude the request operation of foreign domains (or untrusted domain names)

SameSite attributes

SamesiteCookie is a possible alternative to same-origin authentication, but it is not yet mature, and its application scenarios remain to be seen.

  • SameSite=None
    No restrictions, the browser will continue to send cookies under the same site request, cross site request
  • SameSite=Strict
    : Only send cookies when visiting the same site
  • SameSite=Lax
    : If this request is this kind of request (change the current page or open a new page) and it is a GET request at the same time, then this cookie can be used as a third-party cookie

JWT verification

  • The back end generates a Token according to the user, then returns the Token to the front end, and the front end saves the Token
  • When calling other interfaces for interaction, add a request header field and put Token
  • When receiving the Token in the background than verifying whether the Token is consistent

Other preventive measures

  • The get request does not include addition, modification and deletion functions, only query data
  • For users, try to avoid opening suspicious links, or use uncommon browsers to open

The attacker induces the victim to enter a third-party website, and then sends a request to the attacked website on the third-party website. Since the user has cookies on the third-party website and has completed identity verification,


Reference document: Use Fetch

Fetch, as a Http request solution, is an alternative to XHR. Note that Fetch is a Promise-based API, while Axios is a Promise-based library. The usage of Fetch is very similar to that of Axios. Pay attention to the body attribute passed by fetch when requesting a post. , The value is the object converted into a string



Reasons for TCP three-way handshake connection

First of all, we must know what is the purpose of the TCP three-way handshake: in order to ensure that the sending and receiving capabilities of both parties are normal and reliable

  • The reason why two handshake cannot be used: combined with the three-way handshake flow chart, remove the second handshake-if the server responds to the client, the client cannot confirm whether the server has the normal sending function, for example Example: The client showed that a connection request was sent, but due to some reasons, it was consistently on the way of transmission and was not received by the client. At this time, the client will think whether the request was sent incorrectly, and then sent a connection request to the client. Then, by coincidence, the client received the request, and the two parties established a connection, transmitted data, and then disconnected. even. However, at this time, the first connection request sent by the client finally arrived, and the server received it, so the connection was established again, resulting in a waste of server resources
  • The reason for not adopting the four-way handshake: The three-way handshake is completely enough for both parties to confirm whether they can send and receive information normally, and no additional handshake interaction is required.

The reason why TC waved four times

  • The client is sending a disconnect request
    After that, the server cannot respond to the disconnect request in a timely manner
    , You must wait until all the messages on the server side have been sent. This process takes a certain amount of time. Excluding the second response from the server to the client, while waiting for the server to send it out for a long time, if there is no response for a long time, the client will think that the packet is lost, and then send a FIN close request to the server. There will be problems.

Forward proxy and reverse proxy

The forward proxy is the proxy between the client and all other servers (emphasis: all), and the reverse proxy is the proxy between the client and the server proxied by the reverse proxy server (that is, the reverse proxy may proxy 2 Servers, 3 servers, etc.)

  • Forward proxy: multiple users send requests to the proxy server , and then forward them to a target server , such as a ladder over the wall
  • Reverse proxy: A user sends a request to the proxy server , then the proxy server infers the request and sends it to one of multiple servers