Back and forth communication

  1. Back and forth communication

Process of front-end and back-end data interaction: The process of data interaction between the browser and the server

  1. Back end Sends data access pages to the front end

  2. The front end sends data to the back end for user registration

  • Process and concept explanation of communication between front and back ends
  1. The process of communication between the front and back ends

The communication between the front and back ends is done in request-response

  1. Front-end: browser Client: indicates the cli tool of the client that can communicate with the server. Curl HTTPS :www.imooc.com Back-end: indicates the server
  • Communication between the front and back ends

1. Use a browser to access the Web page. Enter the URL in the browser address box and press Enter

When parsing HTML tags, the browser will send a request to the server again for some special tags link/img/script/iframe. But users can use them to send requests to the server for a/ Form

3. Ajax and Fetch

HTTP

I met the HTTP

  1. HTTP Hypertext transfer protocol

HTML: Hypertext markup language

  • Hypertext: Originally a single piece of text, connected by hyperlinks. From the original single text into infinite extension, expansion of hypertext, three-dimensional text
  • HTML, JS, CSS, images, fonts, audio, video, and so on are all transferred between the server and the browser over HTTP (Hypertext Transfer Protocol)
  • Each time the front end communicates with the back end, the front end sends a request to the back end. After receiving the request, the back end can give a response
  • HTTP is a request-response protocol
  1. The process of responding to an HTTP request

The HTTP message

  1. Request packets and response packets

When the browser sends a request to the server, the request itself is information. The request message is the information transmitted when the server sends a response to the browser

  1. HTTP Packet Format

  • request

Request header: start line + header request body

  • The request type

GET request, there is no request body, data is carried through the request header POST request, there is a request body, data is carried through the request body

  • The response

Response header: start line + header response body

HTTP method

  1. The way the browser sends the request is independent of the response

GET, POST, PUT, and DELETE are used to define what operations to take on a resource

  1. Semantics of HTTP methods
methods use Applicable scenario
GET To get the data Obtaining resources (files)
POST Create the data registered
PUT Update the data Modify personal information and password
DELETE Delete the data Delete a comment

These methods have their own semantics, but are not mandatory

  1. RESTful Interface Design

An interface design style that takes full advantage of the semantics of HTTP methods

  • GET personal information from the user ID, using the GET method

www.imooc.com/api/http/ge…

  • GET www.imooc.com/api/http/us…
  • Register a new user, using the POST method

www.imooc.com/api/http/ad…

  • POST www.imooc.com/api/http/us…
  • To modify a user, use the POST method

www.imooc.com/api/http/mo…

  • PUT www.imooc.com/api/http/us…
  • To delete a user, use POST

www.imooc.com/api/http/de…

  • The DELETE www.imooc.com/api/http/us…

GET and POST methods

  1. The semantic

GET: obtains data. POST: creates data

  1. To send data

GET carries data in the request header via the address. The amount of data that can be carried depends on the length of the address

A POST can carry data either in the request header via an address or in the request body, and the amount of data it can carry is theoretically unlimited

GET requests can be used for small amounts of data, and POST requests can be used for large amounts of data

  1. The cache

GET can be cached, POST is not

  1. security

? Username = Alex Neither GET nor POST is secure

Don’t use GET when sending passwords or other sensitive information. This is mainly to avoid being peered at directly by others or finding your password through history

The HTTP status code

  1. What is the HTTP status code

Defines the server’s response to the request, which is returned by the server

  1. Semantics of HTTP status codes

1XX: The request is being processed

2 xx: success

Xx: redirect

  • 301 Moved permanenty, permanent redirection, indicating that the resource has been assigned a new URL
  • 302 Found, temporary redirection, indicating that the resource was temporarily assigned a new URL
  • 303 See Other: indicates that another URL exists for the resource. Use the GET method to obtain the resource
  • 304 Not Modified: indicates that the server allows access to the resource but the request condition is not met
  • 307 Temporary redirect Is the same as 302

4xx: Client error

  • 400 Bad Request: Syntax errors exist in the request packet
  • 401 Unauthorized: The request to be sent requires authentication information that is authenticated through HTTP
  • 403 Forbidden. Access to the requested resource is denied by the server
  • 404 not found: The requested resource was not found on the server
  • 408 Request timeout: The client Request times out
  • 409 ConfICT, requested resources may cause conflicts

5xx: Server error

  • 500 Internal server error: An error occurred when the server executed the request
  • 501 Not Implemented requests were out of the server’s scope
  • 503 Service unavailable: The server is temporarily overloaded or is being stopped for maintenance and cannot be processed
  • 505 HTTP version is not supported, or the server does not support the HTTP version used in the request

303 specifies that the client should use the get method to obtain resources, he will change the POST request to get requests for redirection; 307 will adhere to browser standards and will not change the POST

The local store

cookie

  1. I met a cookie
  • What is a Cookie

Cookie, HTTP Cookie, or Cookie for short, is a way for the browser to store data because it’s stored locally by the user, not on the server, it’s stored locally and it’s automatically sent to the server every time the browser requests it

  • What does a Cookie do

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

  • Manipulate cookies in the browser

Do not save sensitive information such as passwords in cookies

  1. Basic usage of cookies
  • Write a Cookie

document.cookie = ‘username=zs’; document.cookie = ‘age=18’; Note Cannot be set together, only one by one

  • Read the Cookie

console.log(document.cookie); //username=zs; Age =18 reads a string of name-value pairs separated by “;” Separate (a semicolon and a space)

  1. The attribute of the cookie
  • The Cookie’s Name and Value

The name or value of the Cookie if it contains non-English letters, encodeURIComponent() encoding is used when writing, Read using decodeURIComponent() to decode

Cookie = 'encodeURIComponent'} ';Copy the code

General name use English letters, do not use Chinese, value can be used in Chinese, but to code

  • Expiration (expiration) time

For expired cookies, they’re cleared by the browser and if there’s no expiration time set, this Cookie is called a session Cookie and it stays in memory, and when the session ends, when the browser closes, the Cookie disappears and wants to be there for a long time, Sets Expires or max-age Expires to Date

document.cookie = `username=alex; expires=${new Date(
         '2100-1-01 00:00:00'
 )}`;
Copy the code

If the value of max-age is 0 or negative, the Cookie will be deleted document. Cookie = ‘username= Alex; max-age=0’;

The following points can be understood

  • Domain Domain

Domain specifies the scope of Cookie access (different Domain names). If you use JS, you can only read and write cookies of the current Domain or the parent Domain, but cannot read and write cookies of other domains

  • The Path Path

Path specifies the scope of access to the Cookie (under the same domain name). JS can only read and write the Cookie of the current Path and the upper-level Path, but cannot read and write the Cookie of the lower-level Path. path=/course/list’; document.cookie = ‘username=alex; path=/1.Cookie/’; If the Name, Domain, and Path fields are the same, the Cookie is the same

  • HttpOnly

Cookies with an HttpOnly attribute cannot be accessed through JS

  • Secure Flag

Secure specifies that the server can be sent only when HTTPS is used instead of HTTP. Domain, Path, Secure, and cookies that cannot expire can be sent to the server along with the request

  1. Cookie encapsulation (in vscode code)

  2. Precautions for cookies

  • Cookies can be created on both the front and back ends
  • Cookies are limited in number

The number of cookies under each domain name is limited. If you set cookies after the limit of a single domain name is exceeded, the browser will clear the cookies previously set

  • Cookies have a size limit

The storage capacity of each Cookie is small, about 4KB at most

localstorage

  1. What is the localStorage

LocalStorage is also a way for the browser to store data (localStorage). It is stored locally and not sent to the server. There is no limit on the total size of localStorage under a single domain name

  1. Basic usage of localStorage

console.log(localStorage);

  • setItem()

localStorage.setItem(‘username’, ‘alex’);

  • length

console.log(localStorage.length);

  • getItem()

console.log(localStorage.getItem(‘username’));

  • Returns null if the object does not exist
  • removeItem()

localStorage.removeItem(‘username’); Localstorage.removeitem (‘name’);

  • clear()

localStorage.clear(); 3. Use localStorage for automatic filling

const loginForm = document.getElementById('login'); const btn = document.getElementById('btn'); const username = localStorage.getItem('username'); if (username) { loginForm.username.value = username; } btn.addEventListener( 'click', e => { e.preventDefault(); // Data validation // console.log(loginForm. Username. Value); localStorage.setItem('username', loginForm.username.value); loginForm.submit(); }, false );Copy the code

Summary, cookie, localstorage, sessionStorage three similarities and differences

  1. The life cycle
  • Cookie: The expiration time can be set. If the expiration time is not set, the expiration time is closed by default
  • LocalStorage: will be permanently saved unless manually cleared.
  • SessionStorage: valid only in the current web session, will be cleared after closing the page or browser.
  1. Data storage size
  • Cookie: about 4KB
  • LocalStorage and sessionStorage: can hold up to 5MB of information.
  1. The HTTP request
  • Cookies: Are carried in HTTP headers each time. Using cookies to store too much data can cause performance problems
  • LocalStorage and sessionStorage: stored only in the client (browser) and do not communicate with the server
  1. Ease of use
  • Cookie: needs to be packaged by the programmer, the cookie interface is not friendly
  • LocalStorage and sessionStorage: Source interfaces are acceptable and can be repackaged to provide better support for objects and arrays

Ajax

Ajax based

  1. Ajax is what

Ajax is short for Asynchronous JavaScript and XML

  • Asynchrony in Ajax: You can send requests asynchronously to the server without blocking the current page while waiting for a response, and the browser can do its own thing. The browser does not process the response data until the response is successfully retrieved

  • XML (Extensible Markup Language) is a format for transmitting data in front and back end data communication. XML is not used much now. JSON is more commonly used now

  • Ajax is simply an asynchronous communication between the browser and the server

Using Ajax, you can update a part of a page without reloading the entire page: the registration interface

  1. Build an Ajax development environment

Ajax requires a Server environment, and many browsers cannot properly use Ajax Live Server to install native environments in vscode without a Server environment

Basic usage of Ajax

  1. XMLHttpRequest
  • Ajax, for asynchronous communication between the browser and the server, relies on XMLHttpRequest, which is a constructor

Neither XMLHttpRequest nor Ajax is bound to a specific data format

  1. Steps to use Ajax

2.1. Create an XHR object const XHR = new XMLHttpRequest();

When a response is received, the XHR object’s readyStatechange event is triggered, in which the response can be processed

xhr.addEventListener('readystatechange', () => {}, fasle); xhr.onreadystatechange = () => { if (xhr.readyState ! == 4) return; If ((XHR. Status > = 200) & (XHR. Status < 300) | | XHR. Status = = = 304) {/ / console log (' normal use response data); console.log(xhr.responseText); }};Copy the code

The readyStatechange event can also be used with addEventListener, but note that Internet Explorer 6~8 does not support addEventListener. Instead, use XHR directly, preferably before Open for compatibility reasons

  • The readyStatechange event listens for changes in the readyState state

The value ranges from 0 to 4, and there are five states: 0: uninitialized. Open () 1 has not been called: started. Open () has been called, but send() 2: send. Send () has been called, but response 3: received has not been received. Partial response data has been received. 4: Complete. All response data has been received and is ready for use in the browser

2.3. Prepare to send the request

Xhr. open('HTTP method GET, POST, PUT, DELETE', 'address URL https://www.imooc.com/api/http/search/suggest?words=js/index. HTML. / index. The XML. / index. TXT ", true);Copy the code

Calling open does not actually send the request, but merely prepares the request to be sent

2.3. Sending a Request Call Send () Formally sends a request. The parameters of Send () are the data carried by the request body

  1. Use Ajax to complete the front and back end communication
const url = 'https://www.imooc.com/api/http/search/suggest?words=js'; const xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState ! == 4) return; if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { console.log(xhr.responseText); //{"code":200,"data":[{"word":"jsp"},{"word":"js"},{"word":"json"},{"word":"js \u5165\u95e8"},{"word":"jstl"}]} console.log(typeof xhr.responseText); //string } }; xhr.open('GET', url, true); xhr.send(null);Copy the code

A GET request

  1. Carry data

GET requests cannot carry data through the request body, but can carry data through the request header xhr.send(‘sex=male’); No errors are reported, but no data is sent

2. Data encoding If the data carried is not English letters, such as Chinese characters, it needs to be encoded and then sent to the back end, otherwise it will cause garbled characters. EncodeURIComponent () encoding can be used

A POST request

  1. Carry data

POST requests carry data primarily through the request body, but also through the request header

  • If you want to send data, write it directly to the send() argument, usually a string

xhr.send('username=alex&age=18');

  • You cannot pass an object directly; you need to convert it to a string first

xhr.send({username: 'alex',age: 18 });

  1. Data encoding
XHR. Send (` username = ${encodeURIComponent (' zhang ')} & age = 18 `);Copy the code

JSON

  1. JSON is a format for Ajax to send and receive data

JSON full name is the JavaScript Object Notation {” code “: 200,” data “: [{” word” : “the JSP”}, {” word “:” js “}, {” word “:” JSON “}, {” word “, “js \u5165\u95e8”},{“word”:”jstl”}]}

  1. Why do WE need JSON?

JSON comes in three forms, each of which is written like a JS data type and can be easily converted to and from a JS data type

  • JS->JSON->PHP/Java
  • PHP/Java->JSON->JS

Three forms of JSON

  1. Simple valued form

Json the simple value form of JSON corresponds to the basic data types in JS: numbers, strings, Booleans, and NULL

  • Note ① There is no undefined value in the JSON. ② Strings in the JSON must use double quotation marks
  1. Objects form

JSON objects correspond to objects in JS

  • The property name of the OBJECT in JSON must be quoted in double quotes, and the property value must be quoted in double quotes if the property value is a string in JSON, the property name must be quoted in double quotes if strings are involved. Undefined is not supported
  1. An array

JSON arrays correspond to arrays in JS

  • Matters needing attention

    Strings in arrays must be quoted in double quotes

    Whenever strings are involved in JSON, double quotes must be used

    Do not support the undefined

    xhr.open('GET', './arr.json', true);

Common methods of JSON

  1. JSON.parse()

Json.parse () can parse a JSON-formatted string into a valid JSON string

  1. JSON.stringify()

Json.stringify () converts basic JS data types, objects, or arrays into JSON-formatted strings

  console.log(
        JSON.stringify({
          username: 'alex',
          age: 18
        })
      );  //{username:'alex',age:18}
Copy the code
  1. Package localStorage with json.parse () and json.stringify ()

Cross domain

  1. What is cross-domain

Const url = ‘./index.html’;

  http://127.0.0.1:5500
Copy the code

Const URL = ‘www.imooc.com’; const xhr = new XMLHttpRequest();

  Access to XMLHttpRequest at 'https://www.imooc.com/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
Copy the code

A request is sent to a domain. If the domain to be requested is different from the current domain, it is called a cross-domain request

  1. What are different domains and what are co-domains

HTTPS (protocol) ://www.imooc.com (domain) :443 (port number) /course/list…

If the protocol, domain name, or port number is different, it does not matter whether the domain is different from the path

Different domain https://www.imooc.com:443/course/list http://www.imooc.com:80/course/list http://www.imooc.com:80/course/list With domain http://m.imooc.com:80/course/list http://imooc.com:80/course/list http://imooc.com:80 http://imooc.com:80/course/listCopy the code
  1. Why are cross-domain requests blocked

Blocking cross-domain requests is a security policy of the browser itself. The same-origin policy does not prevent cross-domain requests on other clients or servers

  1. Cross-domain solution ① CORS cross-domain resource sharing ② JSONP

Cross-domain resource sharing is preferred with CORS, and JSONP if the browser does not support CORS

CORS cross-domain resource sharing

  1. What is the CORS
  • Access-Control-Allow-Origin: *

Indicates that all domain names are allowed to request it across domains. * is a wildcard character without any restrictions

  • Only cross-domain requests with specified domain names are allowed

Access – Control – Allow – Origin: http://127.0.0.1:5500

  1. (1) The browser sends the request, (2) the back end adds the Access-Control-Allow-Origin header to the response header, (3) the browser receives the response, (4) If the request is from the same domain, the browser does not do anything extra. ⑤ If it is a cross-domain request, the browser will check the response header to see if cross-domain access is allowed. ⑥ If cross-domain access is allowed, the communication is complete. ⑦ If the desired cross-domain domain name is not found or not contained, the response result is discarded

  2. Compatibility with CORS Internet Explorer 10 or later can use CORS

JSONP

  1. The principle of the json

Script tags across domains are not blocked by browsers and JSONP basically uses script tags to load files across domains

  1. Cross-domain implementation using JSONP

The server side ready to json interface www.imooc.com/api/http/js…

Load the JSONP interface manually or dynamically

const script = document.createElement('script'); script.src = 'https://www.imooc.com/api/http/jsonp?callback=handleResponse'; document.body.appendChild(script); Const handleResponse = data => {console.log(data); };Copy the code

XHR object

attribute

  1. ResponseType and response properties

ResponseText can only be used if responseType is not set or responseType = ” or ‘text’

      xhr.open('GET', url, true);

      // xhr.responseType = '';
      // xhr.responseType = 'text';
      xhr.responseType = 'json';
      xhr.send(null);
Copy the code

Internet Explorer 6 to 9 does not support Internet Explorer 10

  1. The timeout attribute

Set the request timeout (in ms) (after xhr.open()) xhr.timeout = 10000; Internet Explorer 6 to 7 does not support this function, but Internet Explorer 8 does

  1. WithCredentials attribute

Specify whether to carry cookies when sending a request using Ajax. By default, cookies are carried when sending a request using Ajax. Xhr. withCredentials = true is not allowed across domains; Whether the Cookie can be successfully carried across domains depends on whether the server agrees or not. IE6~9 does not support it, and IE10 supports it

methods

Xhr.send () is usually used with the abort event (after xhr.send()).

  1. setRequestHeader()

You can set the request header information xhr.setrequestheader (the name of the header field, the value of the header field); (after xhr.open()) the Content-Type field in the request header tells the server, Xhr.setrequestheader (‘ Content-type ‘, ‘application/ X-www-form-urlencoded ‘); xhr.setRequestHeader(‘Content-Type’, ‘application/json’);

The event

  1. The load event

Triggered when response data is available

      xhr.addEventListener(
        'load',
        () => {
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
            console.log(xhr.response);
          }
        },
        false
      );
Copy the code

Internet Explorer 6 to 8 does not support load events

  1. Error event

Triggered when a request error occurs

      xhr.addEventListener(
        'error',
        () => {
          console.log('error');
        },
        false
      );
Copy the code

IE10 support is available

  1. Abort event

Triggered when abort() is called to terminate the request

      xhr.addEventListener(
        'abort',
        () => {
          console.log('abort');
        },
        false
      );
      xhr.open('GET', url, true);
      xhr.send(null);

      xhr.abort();
Copy the code

IE10 support is available

  1. A timeout event

Triggered after the request timed out

      xhr.addEventListener(
        'timeout',
        () => {
          console.log('timeout');
        },
        false
      );
      xhr.open('GET', url, true);
      xhr.timeout = 10;
      xhr.send(null);
Copy the code

IE8 support is available

Ajax advanced

FormData

  1. Submit the form using Ajax

  2. Basic usage of FormData

Create a FormData object from an HTML form element

Const fd = new FormData(form element); xhr.send(fd); Const fd = new FormData(form element); fd.append('age', 18); fd.append('sex', 'male'); xhr.send(fd);Copy the code

Internet Explorer 10 and later are supported

(To be added)

Ajax extensions

axios

  1. What is axios

Axios is a Promise-based HTTP library that can be used in browsers and third-party Ajax libraries in Node.js

www.axios-js.com/zh-cn/docs/

  1. Basic usage of axios

The introduction of axios

const url = 'https://www.imooc.com/api/http/search/suggest?words=js'; Axios (url, {method: 'post', headers: {' content-type ': 'application/x-www-form-urlencoded' // 'content-type ': 'application/json'}, // application/json // data: {// age: 18, // sex: 'male' // } // application/x-www-form-urlencoded data: 'age=18&sex=male' // timeout: 10 // withCredentials: true }) .then(response => { console.log(response); console.log(response.data.data); }) .catch(err => { console.log(err); }); axios .get(url, { params: { username: 'alex' } }) .then(response => { console.log(response); }); axios .post(url, 'username=alex&age=18') .then(response => { console.log(response); }) .catch(err => { console.log(err); });Copy the code

Fetch

Ajax applications

(To be added)