Part ONE: Front and back end interaction and HTTP

1. Communication between front and back ends: The front end proactively communicates with the back end

Front-end and back-end communication refers to the process of data exchange (request-response) between the browser and server: the front-end sends the request data to the back-end, and the back-end responds to the data request after receiving the request from the front-end

  • Front-end and back-end send data (user registration) : the browser submits user registration information in the form of a form, click registration and then send it to the server for processing
  • Back end sends data to the front end (accessing the page): after the user enters the URL and presses Enter, requests some resources to load, and the back end returns the server’s resources for the browser to render

2. Front and rear end communication modes (three)

1. Use the browser to access the page for communication – enter the URL in the browser address bar, press Enter 2. The user clicks a/form to send a request. 3.Ajax and Fetch

3. HTTP browser rendering process

1. After entering the URL and pressing Enter, the user does the following:

  • 1. DNS resolves the domain nameThe url associated IPAddress.
  • 2. Send the TCP connection and locate the corresponding server based on the IP addressThe browser establishes a connection with the server.
  • 3.Sending an HTTP request.
  • 4. ServerResponding to HTTP RequestsThe browser gets the HTML code.
  • 5. The browserParsing HTMLCode, and request resources in HTML code (such as JS, CSS, images, etc.) (get the HTML code before you can find these resources).
  • 6. Browser to the pageApply colours to a drawingPresent to the user.
  • 7. The serverShut downA TCP connection.

2. An important part of the front end is figuring out how the browser renders the page.

  • Step 1: After sending a request to the Web server, the source code in the index.html page is returned
  • Step 2: The browser assigns a main thread that automatically parses and executes code ‘from top to bottom and left to right’
  • Step 3 :(1). When the browser encounterslinkUpon request, a new thread is created to load the resource files (without blocking main thread parsing); (2). If metstyleStyle, normal parsing, parsing dom structure after parsing. (3). If encountered@importAfter the import and parsing is complete, dom rendering will continue, which blocks the main thread
  • Step 4: If a Script tag style is encountered, the main thread takes the resource from the server and parses it, then proceeds to render the DOM structure. Put js last in case JS manipulates the DOM without a value. (You can set the tag async or defer properties to be asynchronous, or put them at the bottom without blocking DOM rendering.)
  • Step 5: Generate DOM tree and CSS render tree
  • Step 6: Generate an HTML rendering tree, refactoring and redrawing the display page

There are two functions:

DOMContentLoaded

The DOMContentLoaded event is fired after the initial HTML document has been fully loaded and parsed, without waiting for the stylesheet, image, and subframe to complete loading. This event is triggered when the DOM tree is available and the JS execution is loaded.

Load event trigger:

The LOAD event is triggered when the JS, CSS, and images in the DOM structure of the page and asynchronously loaded JS, CSS, and images are loaded. There are two concepts:

Refactoring (reflux) : Changes in the size or position of elements that result in a rearrangement of the layout. The process of recalculating the location and size of elements is called refactoring.

  • Trigger refactoring:
  • The first time the page is rendered
  • Element size position changes
  • Adding removes the visible DOM
  • Browser size changes

Redraw: element style changes (color, background and other non-layout changes)

Redraw does not necessarily lead to redraw (reflow), but redraw optimizations are certain:

  • 1. In real project development, if you don’t have a lot of CSS code (or a mobile project), you can use inline styles to reduce HTTP requests and speed up page rendering.

  • Link is placed at the top for faster loading back into the CSS

  • Script is placed at the bottom to retrieve DOM elements or to not block DOM rendering

  • 2. Reduce backflow:

    • Abandon traditional DOM manipulation in favor of vUE data-driven view. Notice the style and animation changes at 🆗
    • Style set changes, multiple styles written in a class, through the class to change the style, you can write the operation style at the end of the DOM tree
    • Cached values can be retrieved directly from the cache if they need to be changedReading and writing separation, and put them in the render queueA rendering
    • The elementBulk changesIf you need to add multiple DOM elements, you can use document fragments or template strings
    • Offline manipulation of DOMThe element leaves the document flow, and then modify the element, which only causes redrawing, not backflow.
    • Apply animations to elements with position property absolute or fixed to avoid affecting the layout of other elements. This is just a redraw, not a backflow.
    • CSS hardware acceleration: Using transform, opacity, and filters triggers hardware accelerators instead of backflow and refactoring

4. Common HTTP method (add, delete, change and check)

HTTP methods that define what to do with a resource have their own semantics, and the way that the browser sends the request has nothing to do with the response. Okay

  • 1.GET GET data – Send data through the request header (URL)

    • The request header carries data
    • The amount of data that can be carried is small
    • Can be cached
    • unsafeIn the request header, the record is cached.
    • GET harmless: Refresh, back, and other browser actions to GET requests are harmless,
  • 2.POST create data (register)

    Submit data to a specified resource for processing requests (such as submitting a form or uploading a file). The data is contained in the request body. POST requests may result in the creation of new resources and/or the modification of existing resources.

    • The request header and request body carry data
    • It’s theoretically infinite
    • Don’t be cached
    • security
    • POST may submit the form repeatedly
  • 3.PUT Update data (modify personal information, change password)

    Data transferred from the client to the server replaces the contents of the specified document. Such as updating an article

  • 4.DELETE DELETE data (DELETE a comment)

    Asks the server to delete the specified page.

  • RESTful interface design

An interface design style that takes full advantage of the semantics of HTTP methods, such as setting up the user interface, adding, deleting, changing and checking the interface are the same, but the backend can determine your corresponding operation according to your request mode.

5 Common HTTP status codes

The HTTP status code defines the server’s processing of the request and is returned by the server.

  • 1xx: indicates that the protocol processing is in the intermediate state and subsequent operations are required
  • From 200 to 299
  • 200 (Success) The server has successfully processed the request. Typically, this means that the server has provided the requested web page.
  • 300~399 Redirection: gives you a new request address, you need to resend the request with the new address
  • 301 Moved Permanently. Permanently redirect
  • 302 Move Temporarily The server currently responds to a request from a web page at a different location, but the requester should continue to use the original location for future requests.
  • You may continue to use it. When this status code is returned, it does not return any resources, but instead tells the browser to fetch the resources in the cache.
  • 400 to 499 The request is incorrect
  • 400 (Error request) Server does not understand the syntax of the request. Modify the request content
  • The 401 (unauthorized) request requires authentication. The server may return this response for a web page that requires login.
  • 403 (Forbidden) The server rejects the request.
  • 404 Not Found
  • 500~599 Server error (server error)
  • 500 Internal Server Error

Part two: Local storage

1.Cookie (set and read in code)

  • Cookies are a way for the browser to store data locally and are automatically sent to the server with each browser request.
  • Cookies are used to track the habits of users to visit the website, such as when to visit, which pages are visited, and how long they stay on each page
  • Do not save sensitive information such as passwords in cookies.
// Can only be written one by one
       document.cookie = 'username=zs';
// Name and Value are required
// For non-English letters, encodeURIComponent() is used for writing and decodeURIComponent() is used for reading


/* Expiration time. The default session Cookie wants to exist for a long time. Set Expires or max-age to a specific time, or to how many seconds will expire */
 document.cookie = `username=alex; expires=The ${new Date('2100-1-01 00:00:00')}`;
 document.cookie = `username=alex; max-age=The ${24 * 3600 * 30}`;


Copy the code

2. localStorage

  • LocalStorage is also a way for the browser to store data (localStorage), it is only stored locally,It will not be sent to the server.
  • A kind ofPersistent storageThat is, data will never expire if it is not manually cleared. It uses key-value pair to store data and saves the data to the corresponding database file according to the domain name. It can hold much more data than a Cookie.
  • SessionStorage is a session-level cache that is cleared when the browser is closed. Note that the scope of sessionStorage isWindow levelIn other words, sessionStorage data stored between different Windows cannot be shared. SessionStorage data only exists in the current browser TAB;

LocalStorage features:

The size is limited to 5MB to 10MB. Sharing data between all tabs and Windows of the same origin; Data is only stored in the client and does not communicate with the server. Data persists and does not expire. The data persists after the browser is restarted. Operations on data are synchronous.

5.1 localStorage Method:
// Add a data item with setItem()
localStorage.setItem('myName'.'Semlinker');

// Get an item from getItem()
// Get nonexistent returns null
let me = localStorage.getItem('myName');

// Remove an item by removeItem()
// Delete a nonexistent key
localStorage.removeItem('myName');

// Remove all data items
localStorage.clear();
Copy the code

Part 3 Ajax

  • Ajax is essentially an asynchronous way for the browser to communicate with the server without blocking the current page while waiting for a response, allowing the browser to do its own thing. The browser does not process the response data until the response is successfully retrieved.
  • Data transfer: Data in JSON format that was previously in XML format.
  • Using Ajax, it is possible to manipulate a certain part of a page without reloading the entire pagePartially updated.

Example â‘  MoOCs registration test; â‘¡ MoOCs search tips

1. Build Ajax development environment (server environment)

Ajax requires a server environment, and many browsers cannot use Ajax properly in a non-server environment. Install Live Server plug-in in vscode to quickly set up the Server environment

2. How to use Ajax

Ajax, for asynchronous communication between the browser and the server, relies on XMLHttpRequest, which is a constructor. The core four steps for sending an Ajax request:

  • 1.createAn XMLHttpRequest instance object.
  • 2.Open theRequest connection, configure request information.
  • 3.Listening to theRequest state – Different states do different things.
  • 4.sendAJAX request, the AJAX task starts until the response body message returns representing the end of the task.
//1. Create XMLHttpRequest instance object
       const xhr = new XMLHttpRequest();       
//2. Open the request connection and configure the request information
       xhr.open('GET'.'url'.true)
/* There are three parameters: the first parameter is HTTP request mode: GET, POST, PUT, DELETE the second parameter is the request address and the third parameter is asynchronous request, true indicates asynchronous request */ 

When a response is received (readyState changes), the readyStatechange event is triggered to determine whether: All response data has been received. ReadyState === 4 Check: Check whether the server processing result is successful according to the status code. xhr.status >= 200) & (xhr.status < 300) || xhr.status === 304 */
        xhr.onreadystatechange = () = > {
            if(xhr.readyState ! = =4) return;
            if ((xhr.status >= 200) & (xhr.status < 300) || xhr.status === 304) {
                   console.log(xhr.responseText); }};//4. Send the request with the data carried by the request body
  xhr.send(null); 
 // For compatibility, the steps can be changed to new, readyStatechange, open, send
Copy the code
  • Ajax GET requests carry data in the URL
      const url ='https://www.imooc.com/api/search/suggest?words=js&username=alex&age=18';
Copy the code
  • Ajax POST requests -POST requests carry data primarily through the body of the request, but also through the request header (which must be a string or JSON object)
      xhr.send('username=alex&age=18');
      xhr.send(JSON.stringify({
        username: 'alex'.age: 18
      }));
Copy the code

7.JSON(object, string, array)

JSON is a format used by Ajax to send and receive data. JSON has three formats: undefined, annotated, and string must be quoted. 1

It must be a valid JSON string, otherwise an error will be reported

2. Json.stringify () converts basic JS data types, objects, or arrays to jSON-formatted strings

     xhr.send(JSON.stringify({
         username: 'alex'.age: 18
       }))
Copy the code

8. XMLHttpRequest object properties

ResponseType: indicates the text of the response:

  • ResponseType is set before it is ready to send and send
  • If responseType is not set, then responseText is the same as responsexhr.responseType='text';
  • When you set responseType to JSON, you need to get the response property;
  • If you know the format returned by the backend is JSON, you do not need to compile it. The system will compile it automatically.

2. Timeout property: Set the timeout time of the request (unit: ms) xhr.timeout = 10000; 3. The withCredentials property: Specifies whether cookies are carried when Ajax requests are sent

Sending requests using Ajax, by default, carries cookies when in the same domain; Xhr. withCredentials = true is not allowed across domains; Ultimately, the success of cross-domain Cookie portability depends on whether the server agrees or not

  • 1.XMLHttpRequest object properties
    • responseTypeSaid: the format of the response data optional json | | text, text, by default Settings must be used after the json response
    • timeout: Sets the timeout period of the request
    • withCredentials: Specifies whether cookies are carried when requests are sent using Ajax
  • 2. The method of XMLHttpRequest
1.Abort () Terminates the current request. This is usually used in conjunction with the ABORT event2.SetRequestHeader () sets the request header information. Xhr.setrequestheader (the name of the header field, the value of the header field) is only necessary to send a POST request. xhr.setRequestHeader('Content-Type'.'application/json');
      // The content-Type field in the request header tells the server what format the browser sent the data in
     
1. Send JSON data
      xhr.setRequestHeader('Content-Type'.'application/json');// The browser sends json data
      xhr.send(
        JSON.stringify({
          username: 'alex'}));//2. Send name-value data
      xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
      xhr.send('username=alex&age=18');

// If this fails, let the back end change the interface
Copy the code
  • 3. The XMLHttpRequest events
    • 3.1. The load event– Triggered when response data is available, without listening for the success of the request (readyState). Simply listen for the success of the response (xhr.status) instead of the xhr.onreadyStatechange event.
    • 3.2. The error event– Triggered when an error occurs in the request (such as an address error, the request was not sent at all)
    • 3.3. Abort event– Call abort() triggered when the request is terminated (IE10 +)
    • 3.4. A timeout event– Triggered after request timeout (IE8 +)

9.FormData– We use FormData when submitting forms with Ajax;

The data collected by FormData can be sent using the xmlHttprequest.send () method.

// Create a FormData object from an HTML form element
      const fd = newFormData(form element); xhr.send(fd);// Add data through the append() method
      const fd = newFormData(form element); fd.append('age'.18);
      fd.append('sex'.'male'); xhr.send(fd); Internet Explorer 10 and later are supportedCopy the code

Part 4 Cross Domain (Browser)

  • Cross domainIt’s sending requests between different domains;
  • Different domainsIf the protocol, domain name, and port number are different, they are different domains.
  • The same-origin policyIs a security policy of the browser that prevents cross-domain requests.

Cross-domain solution: Preferentially use CORS cross-domain resource sharing. If the browser does not support CORS, use JSONP â‘  CORS cross-domain resource sharing â‘¡ JSONP â‘¢ server proxy

1. The first cross-domain solution: CORS cross-domain resource sharing (IE10 for the backend)

  • Set cross-domain permission in the response header on the backend: access-Control-allow-origin: Allows all domain name requests or specified domain name requests.

2. The second cross-domain scheme: Jsonp

The principle of JSONP: Script tags across domains are not blocked by browsers. JSONP mainly uses script tags to load cross-domain files. The disadvantage is that only support for get methods is limited and insecure and may be subject to XSS attacks.

Cross-domain implementation using JSONP:

  • 1. Create a JSONP interface on the back end:https://www.imooc.com/api/http/jsonp?callback=aaaa
  • 2. The front end declares a function whose function name (such as show) is the JSONP interface value and the function parameter is used to receive the requested data.
  • 3. Create one<script>Tag, the interface address is assigned to SRC, and the function name is passed. The callback = show).
  • 4. After receiving the request, the server passes the parameters in the form of a function call.
/ * ready to json on the server interface: https://www.imooc.com/api/http/jsonp?callback=handleResponse * /
/* The front end loads the JSONP interface manually or dynamically */

// Declare the function
      const handleResponse = data= > {
        console.log(data);// Get the data
      };
// It is equivalent to passing arguments to the function through the execution of the function
Copy the code

3. The third cross-domain solution: server proxy

Using the feature that communication between servers does not need cross-domain, we can solve the cross-domain problem in the development environment by setting the server proxy in the vUE.config.js configuration file when using the VUE framework.

// The proxy function of devServer in vue.config.js is configured
module.exports = {
  devServer: {
    proxy: {
    // If your address starts with/API, it will request the address in target
      '/api': {
        target: '<url>'.ws: true.changeOrigin: true.// Whether to enable the proxy
        // This option makes the/API null
         pathRewrite : {
                    '^/api' : ' '
                }
      }
    }
  }
}
Copy the code

Part five axios

Axios official website: Portal

1. What is Axios?

Axios is a Promise-based HTTP library that can be used in browsers and Node.js. The feature creates XMLHttpRequests from the browser to create HTTP request support from Node.jsPromiseAPI intercepts request and response conversion request data and response data cancellation request automatic conversionJSONData clients support XSRF defenseCopy the code

2. Axios usage steps (installation, introduction, use)

  • The AXIos method takes two arguments, the first a URL string and the second a configuration object.
  • The configuration object has a number of parameters, including:
    • Request method, default post.
    • I’m going to ask for headers, and I’m going to tell the server what my format is, and the server will do something different with that format once it gets it.
    • Request header data params, the normal object format, does not need to set the content-Type, but is automatically set according to the format of the parameter you pass.
  • The content-Type in the request header must be set to JSON if the request body data is in object format.
    • Timeout duration
    • Whether the withCredentials need to be used in cross-domain requests. Default false, set to true

3. The public property of axios() is stripped

  <! -- Step 1: Introduce -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
      // Step 2: Configure the default information
      axios.defaults.baseURL = "https://www.imooc.com";
      axios.defaults.headers["Content-Type"] =
        "application/x-www-form-urlencoded";

      // Add request interceptor
      axios.interceptors.request.use(
        function (config) {
          // What to do before sending the request
          return config;
        },
        function (error) {
          // What to do about the request error
          return Promise.reject(error); });Interceptor: Intercepts requests or responses before they are processed by then or catch. Set a response interceptor: [success state] gets the response body information from the result obtained from the server. [failure state] Manually throws an exception
      axios.interceptors.response.use(
        function (response) {
          // Get data from the server
          return response.data;
        },
        function (error) {
          // No data was retrieved from the server
          return Promise.reject(error); });// Step 3: Send your own separate request
      axios
        .get("/api/http/search/suggest? words=js", {
          params: {
            name: "xxxx".age: 19,
          },
        })
        .then((response) = > {
          console.log(response);
        });

      axios
        .post(
          "/api/http/search/suggest? words=js",
          {
            name: "cccccc".age: 123213,
          },
          {}
        )
        .then((s) = > {
          console.log(s);
        });
    </script>
Copy the code