preface

According to the moOCs “Quick Handling of front-end technology and matching big factory interview requirements” course organized by the topic, updated. If you think you’ve got it covered, check out my previous posts on this topic

Take interview questions often

1. What are the common Http status codes

Http status code classification

  • 1XX The server receives a request
  • 2xx Request succeeded
  • 3 xx redirection
  • 4XX Client error
  • 5XX Server error

Common status code

  • 200 The request is processed successfully
  • 204 The request is processed successfully
  • 301 Permanent redirect
  • 302 Temporary redirect
  • 303 temporary redirect and specify that the client requests the resource using the GET method
  • 304 Resources are found, but the client cache resources are still available
  • 400 Syntax errors exist in the request packet
  • 401 (A total of two returns) ① Authentication required (the authentication window is displayed) ② Authentication failed
  • 403 Access is denied because no permission is granted
  • 404 The requested resource could not be found (① the url is wrong ② the server rejected the request without explanation)
  • 500 Internal server resources are incorrect
  • 503 The server is overloaded and shut down for maintenance

2. What are common Http headers

2.1 the Request Headers

  • ①Accept the data style accepted by the browser
  • ② Accept-encoding Specifies the accept-encoding algorithm that can be accepted by the browser, for example, gzip
  • ③ Accept-language Indicates the accept-language accepted by the browser, for example, zh-CN
  • ④Connection: keep-alive A TCP Connection is used repeatedly
  • ⑤ Cookies are used to manage the state of the server and the client directly, which is essentially a pile of data stored on the client
  • ⑥Host is used to realize virtual Host technology
  • ⑦ User-agent for short UA, browser information
  • 8 Content-type Specifies the format of the data to be sent, such as Application/JSON

2.2 the Response Headers

  • ①Content-type Specifies the format of returned data
  • ②Content-length Specifies the size of the returned data, such as the number of bytes
  • ③ Content-encoding Specifies the data compression algorithm, such as gzip
  • ④ Set-cookie The server sends cookies to the client
  • ⑤ cache-control Specifies the Cache mechanism and Cache logic
  • ⑥Expires Controls the expiration date of the cache (also controls the expiration date of the cache, but has been replaced by cache-control)
  • ⑦ Last-modified Time when the server was Last Modified
  • 8 Eatg is a token that can be associated with a Web resource (if the ETag is not changed, the status of 304 is returned and then not returned, which is also the same as last-Modified). Testing Etag is useful mainly for breakpoint downloads.

2.3 Cache-related Headers

  • (1) the cache-control
  • (2) Expires
  • (3) last-modified
  • (4) If-modified-since is sent from the browser as a request header, and is compared with the last-modified on the server side. If the time is consistent, 304 is returned to continue to use, and If the time is inconsistent, the latest resource returned from the server side is used
  • (5) the Etag
  • ⑥ if-none-match When you make the first HTTP request, the server returns an Etag, and when you make the second HTTP request, the client sends an if-none-match, which is the value of the Etag (set by the client who initiated the request). The server then checks whether the Etag sent by the client is the same as the server’s. If so, it sets if-none-match to false and returns status 304. The client continues to use the local cache.

3. Describe the Http caching mechanism

3.1 What is caching?

A resource that opens a web site and does not need to be retrieved from the server because it has not changed is called a cache

3.2 Which Resources can be cached?

Static resources (JS, CSS, Img)

3.3 ①Http Caching — Mandatory caching

The cache logic is controlled by the (cache-control: XXX value) field returned by the server

  • ① Max-age Controls the duration of a resource in seconds
  • ② No-cache forces the client to send requests directly to the server. That is, each request must be sent to the server. The server receives the request and determines if the resource has changed, returns new content if it has, or 304 unchanged if it has not. This can be very misleading and can be mistaken for a response that is not cached. Cache-control: no-cache is actually cached, but the Cache evaluates the validity of the cached response to the server each time it provides response data to the client (browser)
  • ③ No-store disallows all caching.
  • ④ Private is only for individual users and cannot be cached by proxy servers
  • ⑤public indicates that the response can be cached by any cache

3.4 ②Http caching — negotiation caching (contrast caching, server-side caching strategy)

Negotiation cache, also known as contrast cache. After the browser makes the initial request, the server returns the resource and the resource id, and the browser makes the second request with the resource ID to the server. The server compares the received resource ID with the resource ID on the server. If the resource ID is consistent, 304 is returned indicating that the resource can be used. If the resource ID is inconsistent, 200 and the latest resource are returned

Two resource identifiers are commonly used

① Last-modified and corresponding if-modified-since②Etag and if-none-match (a unique identifier for a resource, similar to a human fingerprint)

③ Compare last-Modified and Etag

  • Etag is preferred because it is a unique resource identifier
  • Last-modified is only accurate to the second
  • Etag is more accurate if the resource is generated repeatedly with the same content

3.5 ③ [Http Caching — Overview]

First, the browser sends an Http request. Assuming that cache-control controls the mandatory cache, the browser checks whether the cache expires, for example, max-age

  • ① If there is no expiration within the specified time, the resource cached last time will be read directly and the page will be presented directly. If the mandatory cache expires, the server determines whether the Etag and Last-Modified negotiated cache fields are available. If so, the request is sent with if-none-match, if-Modified-since fields. The server then receives the request to determine whether the cache is still available
  • ② Can be used to return 304 and then read cache, page rendering
  • If not available, 200 and the latest resource will be returned, and the page will be rendered
  • (4) If there is no Etag or Last-Modified negotiation cache field, the Http request will be made directly to request the latest resource, and the server will return the latest resource, and the page will be displayed directly

Write a simple Ajax by hand

At the heart of Ajax technology is the XMLHttpRequest object. I won’t go into XMLHttpRequest in detail here, but I’ll cover some of the things that are involved in handwriting methods.

4.1 the open () method

The open() method is used to initialize a request. The open() method takes three arguments:

  • The first parameter method: the type of request to send. Such as GET, POST, PUT, DELETE, etc.
  • The second parameter URL: the REQUESTED URL.
  • The third parameter async: a Boolean value for whether to send the request asynchronously. True: sends the request asynchronously.

4.2 readyState property

The readyState property represents the current active phase of the request/response process. The values of this attribute are as follows:

  • 0 (UNSENT) is not initialized. The open() method has not been called
  • 1 (OPENEDStart). The open() method has been called, but the send() method has not
  • 2 (HEADERS_RECEIVEDSent). The send() method has been called, but no response has been received
  • 3 (LOADINGReceived). Partial response data has been received
  • 4 (DONECompleted). All response data has been received
function ajax ( url , successFn ){

    const xhr = new XMLHttpRequest()
    xhr.open( 'GET' , url , true)
    // true asynchronous to avoid jamming, false synchronous
  xhr.onreadystatechange = function() {  if( xhr.readyState == 4) { if( xhr.status == 200) { successFn(xhr.responseText)  }  }  }   xhr.send(null) } Copy the code

5. Write an Ajax request with a promise

function ajax(url) {
    const p = new Promise((resolve, reject) = > {
    
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
 // true asynchronous to avoid jamming, false synchronous   xhr.onreadystatechange = function () {  if (xhr.readyState === 4) {   if (xhr.status === 200) {  resolve(JSON.parse(xhr.responseText));  } else if (xhr.status === 404) {  reject(new Error("404 not found"));  }   }  };   xhr.send(null);  });  return p; } Copy the code

6. What is cross-domain and why do cross-domain problems occur

The browser rejects cross-domain requests because of the same origin policy

The same-origin policy

  • When making an Ajax request, the browser requires that the current web page and the server server must be of the same origin (security issue)
  • Cognate: The protocol, domain name, and port must be the same
  • For example: front-end:http://a.com:8080/, the backend:https://b.com/api/xxxIn this case, the front-end protocol ishttp, domain name fora.com, the port is8080, the protocol at the back end ishttps, domain name forb.com, the port is not written, but HTTPS is used by default443Port, so all three are different, and if one of them is different, the browser will intercept the request, and that’s a cross-domain problem

7. How to solve cross-domain problems

All cross-domains must be approved and coordinated by the server. If cross-domains are implemented without the permission of the server, the browser has vulnerabilities, which is a danger signal. Common cross-domain solutions include JSONP, CORS, and proxy cross-domain. Here we will only briefly explain JSONP

JSONP

  • 1.<script>Cross-domain restrictions can be crossed
  • ② The server can return arbitrary dynamic Mosaic data
  • 3. So,<script>You can get cross-domain data, as long as the server is willing to cooperate with the return

For a simple example, an HTML file

<script>
 window.callback = function (data) {
     console.log(data)
    }
</script> <script src="http://localhost:8080/jsonp.js"></script> Copy the code

The json. Js file

callback({ name: "zhangsan" })
Copy the code

For cross-domain details, please refer to this article for further cross-domain problems

8. Describe the differences between cookie, localStorage, and sessionStorage

cookie

  • ① It is used for communication between the browser and the server
  • ② Is borrowed to local storage, can passdocument.cookie=" "Set up the

    Disadvantages:

  • ① the maximum storage size is 4KB
  • (2) Http requests need to be sent to the server to increase the amount of requested data

LocalStorage and sessionStorage

  • ①HTML5 is specifically designed for storage, with a maximum capacity of 5M
  • The API is simple and easy to use.localStorage.setItem(' ',' '),localStorage.getItem(''),sessionStorage.setItem(' ',' '),sessionStorage.getItem('')
  • ③ Will not be sent out with the Http request
  • (4) the difference between:localStoragePermanently, unless manually removed from the console,sessionStorageExists in the current session and is cleared when the browser is closed

At the end of the article

If you think my writing is good, you can give me a thumbs up. If there is anything wrong or bad, please comment and point out so that I can correct it. (This series is coming to an end. Review the previous ones.)

Other articles

  • Front end basics ④ – events and DOM
  • ③ Asynchronous (Interview scenario)
  • Front End Basics ② — Scopes and closures
  • Front end basic knowledge ① — CSS interview questions
  • Gluten series ① — Didi SP side interview question
  • Gluten series ② — Didi intern cool the meridian

This article is formatted using MDNICE