Challenge front-end knowledge points http / ECMAScript


Nezha’s life creed: if you like what you learn, there will be strong power support.

Learning programming every day makes you a step away from your dream. Thank every programmer who loves programming. No matter how wonderful the knowledge is, join me to settle down like a wandering heart, keep going, come on,2021come on. Welcome to join mevx:xiaoda0423, welcome to like, collect and comment

Don’t be afraid of dreaming, but don’t just dream. Be a doer, not a talker, and strive for truth.


I hope this article can help you. (thanks for one button three connections). Have you accepted the challenge?

Challenge front-end knowledge points http / ECMAScript

About HTTP module

1. Talk about your understanding of HTTP and HTTPS, and what are their port numbers

Well, HTTP is a hypertext transmission protocol. It is a stateless application layer protocol based on request and response. It often transmits data based on TCP / IP protocol. It is the most widely used network protocol on the InternetwwwDocuments must comply with this standard and designHTTPThe original intention of is to provide a way of publishing and receivingHTMLThe method of the page.

HTTPIt is a widely used network transmission protocol. It is the application layer communication protocol or standard TCP between the client browser or other programs and the web server. It is used to transmit hypertext from the WWW server to the local browser. It can make the browser more efficient and reduce network transmission.

thatHTTPSIt is a transmission protocol for complete communication through computer networkHTTPCommunicate withSSL/TLSEstablish communication and encrypt data packets.HTTPSThe main purpose of using is to provide identity authentication to the website server and protect the privacy and integrity of exchange data.

HTTPS is an encrypted version of HTTP, which aims at security. InSSL is added to HTTP, and the security basis is SSL.

TLSIs a transport layer encryption protocol, formerly known asSSLagreement.

HTTPUsually carried inTCPAbove, inHTTTPandTCPAdd a security protocol layer between(SSLorTSL), that’s what we often sayHTTPS

HTTP features:

Support client or server mode, C / S mode;

It is simple and fast. When the client requests services from the server, it only needs to transmit the request method and path. Common request methods areGET,HEAD,POST, each method specifies different types of contact between the client and the server. Due to the simple HTTP protocol, the program scale of the HTTP server is small, so the communication speed is very fast;

It is flexible. HTTP allows any type of data object to be transmitted. The type being transmitted is determined byContent-TypeMarking;

No connection means that only one request is processed for each connection. After the server processes the client’s request and receives the client’s response, it will disconnect. This method can save transmission time;

Stateless,HTTPThe protocol is a stateless protocol. Statelessness means that the protocol has no memory ability for transaction processing. The lack of state means that if the subsequent processing needs the previous information, it must be retransmitted, which may lead to the increasing amount of data transmitted each connection. On the other hand, when the server does not need the previous information, its response is faster.


It adopts mixed encryption technology. The middle cannot see the plaintext content and encrypts the content;

The identity is verified, and the client accesses its own server through certificate authentication;

It can prevent the transmitted content from being impersonated or tampered with by intermediaries, and ensure the integrity of the data.

HTTPofURLSohttp://At the beginning, forHTTPSofURLSohttps://start;HTTPIt’s not safe, andHTTPSIs safe;HTTPUnable to encrypt, andHTTPSEncrypt the transmitted data;HTTPNo certificate required, andHTTPSneedCAIssued by the agencySSLCertificate.

Their port numbers are:

HTTPThe default port number is80HTTPSThe default port number is443

thatHTTPSMore secure because: in network requests, many servers and routers need to forward. All nodes may tamper with the information, and if HTTPS is used, the key is only available at the terminal. HTTPS is safer than HTTP because it usesssl/tlsProtocol transmission. It includes certificate, unloading, traffic forwarding, load balancing, page adaptation, browser adaptation, refer delivery and other technologies to ensure the security of the transmission process.

https, full nameHyper Text Transfer Protocol Secure, comparehttp, one moresecure, this onesecureIs provided by TLS (SSL).httpsandhttpAll belong toapplication layer, based ontcpas well asudpAgreement, but it’s completely different.

HTTP is the format specification of data transmission between client and server, which means “Hypertext Transfer Protocol”


  1. Stateless protocols have no memory for transactions, and lack of status indicates that if subsequent processing is required, the information provided above is required
  2. The way to overcome the defect of stateless protocol is throughcookieAnd session save information

2.http/2How much do you know

HTTP/2The concept of “server-side push” is introduced, which allows the server to actively send data to the client cache before the client needs data, so as to improve the performance.

HTTP/2Provide more encryption support. Using multiplexing technology, multiple messages are allowed to cross over on another connection at the same time. Header compression is added, so the request is very small and the request and response are very fastheaderWill only use a small proportion of bandwidth.

http/2The protocol is based onhttpsYes, sohttp/2The security of is also guaranteed.

Head compression:http/2If you send multiple requests at the same time and their headers are the same or similar, the protocol will help you eliminate the duplicate parts.

abouthttp/2No longer use imagehttp/1.1The message is in plain text form, but in binary format. Header information and data body are binary, collectively referred to as frame, header information frame and data frame.

Data flow:http/2The data packets are not sent in sequence. Consecutive data packets in the same connection may belong to different responses. The data packet must be marked to indicate which response it belongs to. All packets of each request or response are called a data flow.

Multiplexing:http/2It is possible to concurrent multiple requests or responses in a connection without one-to-one correspondence in orderhttp/1.1The serial request in does not need to queue, so there will be no queue head blocking problem, which reduces the delay and greatly improves the utilization of the connection.

Server push,http/2The request response mode of transmission is improved. The server is no longer a passive response, but can also automatically send information to the client.

http2The problem occurs in multiplehttpRequest is reusing atcpConnection, lowertcpI don’t know how many agreements there arehttpThe request will be triggered in case of packet losstcpRetransmission mechanism, such atcpAll in the connectionhttpRequests must wait for the lost packet to be retransmitted.

First,http/1.1If a request in the pipeline transmission is blocked, all requests after the queue are blocked. Second,http/2Multiple requests reuse onetcpIn case of packet loss, all connections will be blockedhttpRequest.

3. Talk about the common status codes of HTTP

Five categories of HTTP status codes:

1xx: prompt information, indicating that the current protocol processing is in the intermediate state, and there are subsequent operations

2xx: successful, the message has been received and processed correctly,200, 204, 206

3xx: redirection. The resource location changes. The client needs to resend the request

4xx: client error, request message error, server unable to process

5xx: server error, the server encountered an internal error while processing the request

  1. 100 ContinueIndicates to continue. Generally, when sending a post request, after the HTTP header has been sent, the server will return this information to confirm, and then send the specific parameter information.
  2. 200 okIndicates normal return information.
  3. 201 CreatedIndicates that the request was successful and the server created a new resource
  4. 202 AcceptedIndicates that the server has accepted the request but has not yet processed it
  5. 301 Moved PermanentlyIndicates that the requested page has been permanently moved to a new location
  6. 302 FoundIndicates a temporary redirect
  7. 303 See OtherRepresents a temporary redirect and is always usedGETRequest newURI
  8. 304 Not ModifiedIndicates that the requested web page has been modified since the last request
  9. 400 Bad RequestIndicates that the server cannot understand the format of the request, and the client should not try to send the request with the same content again.
  10. 401 UnauthorizedIndicates that the request is not authorized
  11. 403 ForbiddenIndicates that access is prohibited
  12. 404 Not FoundIndicates that no resource was found to match the URI
  13. 500 Internal Server ErrorRepresents the most common server-side error
  14. 503 Service UnavailableIndicates that the server cannot process the request temporarily

4. TalkhttpTransaction flow

The first step is domain name resolution; The second step is to initiatetcpThree handshakes; The third step is to establishtcpInitiate after connectionHTTPRequest; Step 4: server side responseHTTPRequest, the browser getsHTMLcode; Step 5: Browser parsingHTMLCode and requestHTMLResources in the code; Step 6: the browser renders the page and presents it to the user.

5. Simple HandwritingHTTPThe server

var http = require('http');

http.createServer(function(req, res){
 res.writeHead(200, {'Content-Type': 'text/html'});
 res.write('<meta charset="UTF-8"><h1>dadaqianduan</h1>');

6. TalkhttpWhat parts does the request message and response message contain

The request message consists of three parts:

1. Request line, including request method,URI,HTTPVersion information

2. Request header field

3. Request content entity

The request message consists of three parts:

1. Status line, includingHTTPVersion, status code, Reason Phrase of status code

  1. Response header field
  2. Response content entity

7. What is reverse proxy

Reverse proxy,Reverse Proxy, refers to receiving the connection request on the Internet through the proxy server, then forwarding the request to the server on the internal network, and returning the results obtained from the server to the client requesting the connection on the Internet. At this time, the proxy server appears as a reverse proxy server.

8. What are the request methods in HTTP

GET, request to access the resources identified by URI and uniform resource identifier, and pass parameter data to the server through URL

POSTThe main function of transmitting information to the server is similar to the get method, but the amount of data transmitted is usually unlimited.

PUT, transfer the file. The message body contains the file content and saves it to the corresponding URI location.

HEAD, get the message header, which is similar to the get method, but does not return the message body. It is generally used to verify whether the URI is valid.

DELETE, delete the file. Contrary to the put method, the file corresponding to the URI location is generated

OPTIONS, query the HTTP methods supported by the corresponding URI

9.HTTPIn the agreement1.0Version specification and1.1Differences between versions and specifications

stayhttp1.0In, after establishing a connection, the client sends a request, the server returns a message and closes the connection. When the browser requests next time, it will establish a connection again. This method of continuously establishing a connection will cause many problems.

stayhttp1.1The concept of continuous connection is introduced. Through this connection, the browser can send a request and get the return information after establishing a connection, then continue to send the request and wait for the return information again. The client can send multiple requests continuously without waiting for each response.

10.HTTPWhat types of header fields are included

General header field, which will be used by both request message and response message

  1. Date, the time when the message was created
  2. Connection, connection management
  3. Cache-Control, cache control
  4. Transfer-Encoding, transmission coding mode of message body

Request header field, the header field that the request message will use

  1. Host, the server where the request resource is located
  2. Accept, media types that can be processed
  3. Accept-Charset, acceptable character set
  4. Accept-Encoding, acceptable content encoding
  5. Accept-Language: acceptable natural language

Response header field, the header field that the response message will use

  1. Accept-Ranges, acceptable byte range
  2. LocationTo redirect the client to the URI
  3. Server, installation information of HTTP server

Entity header field, the header field used by the entity part of request message and response message

  1. Allow, HTTP methods that resources can support
  2. Content-Type, type of entity principal
  3. Content-Encoding, the encoding method used by the entity body
  4. Content-Language, natural language of entity subject
  5. Content-Length, bytes of entity body
  6. Content-Range, the location range of the entity body, which is generally used when issuing partial requests

11. Andhttpscomparison,httpWhat are the disadvantages

httpThe disadvantages are: the communication uses plaintext and is not encrypted, and the content may be eavesdropped, that is, packet capture analysis; Failure to verify the identity of the communicating party may be disguised; The integrity of the message cannot be verified and may be tampered with.

httpsnamelyHTTP + encryption + authentication + integrity protection

12. How to optimizeHTTPrequest

Optimize and accelerate with load balancingHTTPApplication request, usingHTTPCache to optimize site requests

13. What are the characteristics of HTTP protocol

It supports client or server mode, which is simple, fast, flexible, connectionless and stateless.

14.HTTP1.1What’s new in version

The default persistent connection saves traffic, as long as either end of the client or server does not explicitly indicate disconnectionTCPIf you are connected, you can always keep connected and send multiple timesHTTPRequest.

Pipelining, the client can send multiple messages at the same timeHTTPRequests instead of waiting for responses one by one.

Breakpoint continuation principle.

15.tcpThree handshakes and four waves of transmission

After three handshakes and sending the data packet through TCP,tcpIt will not ignore the transmitted data. It will certainly confirm whether it has been successfully delivered to the other party. The TCP flag is used in the handshake process, which isSyn and ACK

The sender first sends a band to the receiverSYNMarked packet. After receiving, the receiving end returns a message withSYN/ACKMark the data package to indicate correct communication and confirm the information. Finally, the sender returns a bandACKThe packet marked represents the end of the “handshake”. If it is inexplicably interrupted at some stage in the handshake process,TCPThe same packets are sent again in the same order.

Disconnect oneTCPConnection requires “four handshakes”

First handshake: the active closing party sends a fin to close the data transmission from the active closing party to the passive Closing Party, that is, the active Closing Party tells the passive closing party that the active closing party will no longer send data to the passive Closing Party, but at this time, the active closing party can also receive data.

Second handshake: received by the passive Closing PartyAfter fin package, send a message to the other partyACK, confirm that the serial number is the received serial number+1. Same as syn, oneFINOccupy a sequence number.

Third Handshake: received by the passive Closing PartyFINThe packet is used to close the data transmission from the passive closing party to the active Closing Party, that is, to tell the active closing party that the data of the passive Closing Party has been sent and will not be sent to the active closing party.

The fourth Handshake: after the active closing party receives the fin, it sends a handshake to the passive closing partyACK, confirm that the serial number is the received serial number+1

16. Tell us the difference between TCP and UDP

tcpTransmission control protocol is a connection based protocol, that is, a reliable connection must be established with the other party before sending and receiving data formally. OnetcpThe connection must go through three conversations before it can be established.

udpUser datagram protocol is the protocol corresponding to TCP. It is a non connection oriented protocol. It does not establish a connection with the other party, but directly sends the data packet.udpIt is applicable to the application environment where only a small amount of data is transmitted at a time and the reliability requirement is not high.

17. One page from inputurlWhat is sent to the process of page loading display completion

When sending aurlWhen requested, thisURL is webThe URL of the page is also the URL of each resource on the web pageurl, the browser will start a thread to process the request, and start a DNS query on the remote DNS server, which can enable the browser to obtain the IP address corresponding to the request.

Browser and remotewebServer passtcpThree handshake negotiations to establish atcp/ipconnect. The handshake includes a synchronization message, a synchronization response message and a response message. The three messages are transmitted between the browser and the server. The handshake first attempts to establish communication by the client, then the server responds and accepts the request of the client, and finally the client sends the message that has accepted the request.

oncetcp/ipWhen the connection is established, the browser will send a message to the remote server through the connectionHTTP get request, the remote server finds the resource and returns it with an HTTP response. The HTTP response status code with a value of 200 indicates a correct response.

The web server provides resource services. The client starts downloading resources. After the request is returned, it enters the browser module, and the browser will parse itGenerate DOM tree from HTMLSecondly, according toCSS generate CSS rule tree, andJavaScript can operate the DOM according to the DOM API

18. What are the seven layers of the network layering model

  1. Application layer: a means to allow access to the OSI environment
  2. Presentation layer: translate, encrypt and compress data
  3. Session layer: establish, manage and terminate sessions
  4. Transport layer: provide end-to-end reliable message transmission and error recovery
  5. Network layer: responsible for the transmission of data packets from source to destination and Internet Interconnection
  6. Data link layer: assemble bits into frames and realize point-to-point transmission
  7. Physical layer: transmit bits through media to determine mechanical and electrical specifications

19. Tell me304Principle of caching

The server first generates for the requestETag, the server can use it to determine whether the page has been modified in a later request. In essence, the client sends the token back to the server and asks the server to verify whether its client is cached.

304 yesHTTPStatus code. The server uses it to identify that the file has not been modified and does not return content. After receiving a status code, the browser will use the file cached by the browser.

The client requests page a, the server returns page A and adds an Etag to a. the client presents the page and caches the page together with the Etag. The client requests page a again and passes the Etag returned by the server to the server. The server checks the Etag and determines that the page has not been modified since the last client request, and directly returns the response 304 and an empty response body.

Es module

20. Summarize the limitations of the strict model

  1. Variables must be declared before use
  2. The parameter of the function cannot have a parameter with the same name, otherwise an error will be reported
  3. out of commissionwithsentence
  4. You cannot assign a value to the read-only attribute, otherwise an error will be reported
  5. Octal numbers cannot be used, otherwise an error will be reported
  6. Special characters cannot be used
  7. out of commissiondeleteTo delete variables, methods, etc., you can only usedeleteDelete an object’s properties
  8. evalVariables are not introduced in its outer scope
  9. Eval and argumentsCannot be reassigned
  10. argumentsChanges in function parameters are not automatically reflected
  11. out of commissionarguments.callee
  12. out of commissionarguments.caller
  13. prohibitthisPoint to global object
  14. out of commissionFn.caller and fn.argumentsGets the stack of function calls
  15. Added reserved words

21. Tell mees6

  1. New template string${}
  2. Arrow function
  3. for-of
  4. Get syntax substitution for remaining parametersargumentsobject
  5. Define default parameter syntax
  6. es6takePromiseObjects are incorporated into the specification and provide nativePromiseobject
  7. IncreasedletKeyword to define the variables of the block scope
  8. IncreasedconstTo define constants
  9. IncreasedSymboldata type
  10. introducemoduleModule concept

22.PromiseWhat are the characteristics

es6Native providesPromiseObject, which is used to handle asynchronous operations.

PromiseObject characteristics:

The state of the object is not affected by the outside world,The promise object has three states: pending, in progress, resolved, completed, rejected, and failed, only the result of asynchronous operation can determine the current state, and no other operation can change this state.

Once the state changes, it will not change again. This result can be obtained at any time.There are only two possibilities to change the promise object: from pending to resolved and from pending to rejected。 Only in these two cases, the state is fixed, the result will always be maintained, and will not change again.

Even forPromiseAdding a callback function to the object will also get this result immediately, which is completely different from the event. The characteristic of the event is that if you miss it and listen again, you can’t get the result.

YesPromiseObject, the asynchronous operation can be expressed in the process of synchronous operation, avoiding the callback functions nested in layers. In addition,PromiseObject provides a unified interface, which makes it easier to control asynchronous operations.

Disadvantages: cannot cancelPromise, once a new one is created, it will be executed immediately and cannot be cancelled halfway. If the callback function is not set,PromiseErrors thrown internally are not reflected externally.

23. TalkPromiseUnderstanding of

Three states:

PendingRefers to the initial state, notFulfilledorRejectedstate

ResolvedRefers to a successful operation

RejectedRefers to a failed operation

let p = new Promise(resolve, reject) => {
 if(condition) {


24.es6 implementation of array de duplication

// es5
var varr [1,2,3,4,3,4,5,5,3]
function removeDa(arr){
 var obj = {};
  obj[item] = true
 return Object.keys(obj);
// es6
let removeDa = arr => [...{new Set([...arr]))];

25. ES6 use to exchange two numbers

let a = 1, b = 2;
[a,b] = [b,a];
console.log(a); // 2
console.log(b); // 1

26. Whyes6

First: in line with future trends; Second: improve development efficiency; Third: reduce the amount of code and improve readability.

27. How to make the browser support in the development environmentes6


28.es6inletDoes keyword support block level scope

var arr = [];
for (var i = 0; i < 5; i++){
 arr[i] = function(){
arr[3](); // 5

let arr = [];
for(let i = 0; i < 5; i++) {
 arr[i] = function() {
arr[3](); // /5

letbyJavaScriptA block level scope is added, and the variables declared with it are only inletThe keyword is valid within the code block.

29. Code example

var obj = {
 // es5
 fn1: function() {
 fn2:() => {
obj.fn1(); // obj
obj.fn2(); // window

30.superWhat is it?

It is a keyword. Its usage issuper(...)perhapssuper.xx(...)

superSyntax definition andthisDifferent,thisIs defined asthisThis keyword will be replaced with a reference, andsuperthen issuper(...)Will be replaced with a call. In addition to being able toconstructorDirectly called insuperIn addition, you can also usesuper.xx(...)To call a prototype method on the parent class, which is also a qualified syntax.

31. Code example

 var x:
 var y = x;
 x = 2;
 return [x,y,fn()];


32. Code example

// ['outer','outer']

33. Code example

 let a = this?class b{} : class c{};
 console.log(typeof a, typeof b, typeof c)
// function undefined undefined

34. Code example

(typeof (new (class { class () {} })))
// object
var Test = class{
var test = new Test();
typeof test;

35. Code example

let f={g()=>1};
return typeof f;
// error

36. What isDOMTemplate

domThe template is originally written on the page and can be recognized by the browserhtmlAs a result, when loaded, it will be rendered by the browser. So followHTMLStructure and label naming, otherwise it cannot be parsed by the browser, and the content cannot be obtained, and then useJavaScriptobtainDOMThe content of the node is formedDOMTemplate.

37. What is a string template

The string template may have been originally placed on the serverscriptIn the label, asJavaScriptString and does not participate in page rendering, so it may not careHTMLStructure and label naming, as long as the corresponding structure is generated according to the template and the naming conforms toHTMLstandard.

38. Please tell the difference between the extension operator and the remaining operator

To some extent, the remainder operator is the opposite of the extension operator. The extended operator will “expand” the array into multiple elements, and the remaining operators will collect multiple elements and “compress” them into a single element.

39.var,let,constDifference between declared variables

varDeclared variables do not support block scope, support declaration prefix, can be defined repeatedly, and the value can be changed.

letDeclared variables support block scope, do not support declaration prefix, cannot be defined repeatedly, and the value can be modified.

constDefine constants. Declared constants support scope, do not support declaration prefix, cannot be defined repeatedly, and values cannot be modified. Values are usually of value type and cannot be used to define circular variables.

40. Deconstruction classification

Object deconstruction; Array deconstruction; Mixed deconstruction; Parameter deconstruction.

41.es6ofextendsDo you support multiple inheritance

es6Multiple inheritance is not supported, but it can be simulated by mixing and other technologies. Once multiple inheritance is used, the attribute methods with the same name will be overwritten in the order of declaration.

42. Remaining parameters andargumentsObject differences

The remaining parameters contain only those arguments without corresponding formal parameters, andargumentsObject contains all the arguments passed to the function.

argumentsObject is not a real array, and the remaining parameters are realArrayInstance, on which all array methods can be used directly.

argumentsObject also has some additional properties.

If you want toargumentsObject, first convert it to a real array.

43.for..ofA little what

Have the samefor...inSimple syntax, but nofor...inDisadvantages of

differforEachMethod can be used withbreak,continue,returnUse together

It provides a unified operation interface for traversing all data structures

44. Why can’t modifiers be used for functions

Modifiers can only be used for classes and methods of classes, not functions, because function promotion exists

45.IteratorWhat is the purpose of the interface

It provides a unified access mechanism for all data structures,for..ofloop

When usedfor...ofWhen a loop traverses a data structure, the loop automatically looks forIteratorInterface.

46. What should I pay attention to when using external module scripts

The code is run in the module scope, not in the global scope. The top-level variables inside the module are not visible externally.

With or without a statementuse strict, module scripts are automatically in strict mode

In the module, you can useimportCommand to load other modules, you can also useexportCommand output external interface

In the module, the top levelthisKeyword returnundefined, not pointingwindowThat is, it is used at the top level of the modulethis, is meaningless.

If the same module is loaded multiple times, it will be executed only once.

47.IteratorFunction and traversal process of

First, provide a unified and simple access interface for various data structures

Second, the members of the data structure can be sorted in a certain order

Third,ES6Created a new traversal commandfor...ofLoop. The iterator interface mainly providesfor...ofuse


Create a pointer object that points to the starting position of the current data structure, that is, the traverser object is essentially a pointer object.

The name of the first call to the pointer objectnextMethod to point the pointer to the first member of the data structure

The second call to the pointer objectnextMethod, the pointer points to the second member of the data structure

Continuously calling the pointer objectnextMethod until it points to the end of the array structure. Every callnextMethod will return the information of the current member in the data structure.

48.asyncFunctions have several forms of declaration

Function declaration

async function da(){}

Expression declaration

var bar = async function () {}

By object declaration

var obj = {
 async daFun(){}

Declaration by arrow function

var da = async() =>{}

49.asyncFunction, how to handle error statements


async function demo() {
  await doSomeThing();
 } catch(err){

add tocatchCallback function

async function demo() {
 await doSomeThing().cache(err=>console.log(err))

50.es6In,generatorFunctionalthrowHow to use the method

throw()Will recovergeneratorAnd throws an exception at the execution point

throw()Follownext()Will return{value,done}, only the exceptions that will be thrown are handled,generatorThe function body will actually executethrow()

Likes, favorites and comments

I amJeskson(dada front end), thank you for your praise, collection and comments. See you next time! (if there are some mistakes in the content of this article, welcome to point out ☞ thank you for learning together)

See you next time!

The article is continuously updated. You can search “programmer Doraemon” on wechat, read it for the first time, and reply to [data] there are the first-line large factory data I have prepared. This article included

githubIncluded, welcomeStar

Recommended Today


Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]