8000 words introduction ECMAScript 6.0 (gray article ~)

Posted by bjazmoore on Thu, 28 Oct 2021 18:23:01 +0200

1. ES6 Foundation

1.1 what is ES6

ECMAScript 6.0 (hereinafter referred to as ES6) is the next generation standard of JavaScript language, which has been officially released in June 2015. Its goal is to make JavaScript language can be used to write complex large-scale applications and become an enterprise development language.
The standard maker has a plan to publish the standard once a year in the future, and the year of use is used as the version. Because the first version of ES6 was released in 2015, it is also called ECMAScript 2015 (ES2015 for short).

1.2 relationship between ES6 and JavaScript

In November 1996, Netscape, the creator of JavaScript, decided to submit JavaScript to ECMA (European Computer Manufacturers Association), hoping that this language can become an international standard. The next year, ECMA released the first version of standard document No. 262 (ECMA-262), which stipulated the standard of browser scripting language and called this language ECMAScript. This version is version 1.0

The standard was formulated for the JavaScript language from the beginning, but it is not called JavaScript for two reasons. First, trademark. Java is a trademark of Sun company. According to the license agreement, only Netscape company can legally use the name JavaScript, and JavaScript itself has been registered as a trademark by Netscape company. The second is to reflect that the language is formulated by ECMA, not Netscape, which is conducive to ensuring the openness and neutrality of the language.

Therefore, the relationship between ECMAScript and JavaScript is that the former is the specification of the latter and the latter is an implementation of the former (other ECMAScript dialects include Jscript and ActionScript). In everyday situations, the two words are interchangeable

ECMAScript is a syntax specification standardized by ECMA (a standards organization similar to W3C).
ECMAScript defines:

Language syntax – syntax parsing rules, keywords, statements, declarations, operators, etc
Type – Boolean, number, string, object, etc
Prototype and inheritance
Standard libraries of built-in objects and functions – JSON, Math, array methods, object introspection methods, etc.

ECMAScript standard does not define functions related to HTML or CSS, nor does it define web APIs similar to DOM (document object model), which are defined in independent standards. ECMAScript covers the usage scenarios of JS in various environments, whether browser environment or non browser environment similar to node.js

1.3 basic grammar

1.3.1 declared variables

//Define variables
//1) var declares a common variable
//2) let declare local variables (block level variables)
//3) const declaration constant
var a1 = 1;
let a2 = 2;
const a3 = 3;

  • et declare local variables

    • ES6 adds the let command to declare variables. Its usage is similar to var, but the declared variables are only valid in the code block where the let command is located.
  • const declaration constant
    *const declares a read-only constant. Once declared, the value of the constant cannot be changed.
    *Declare a variable with const command. This variable must be initialized immediately and cannot be assigned later. Otherwise, an error will be reported.
    *const has the same scope as the let command: it is valid only within the block level scope where the declaration is located

1.3.2 template string

  • Template string to simplify string patching
//ES5, string patching
var str = "<table>" +
            "<tr>" + 
              "<td>title</td>" + 
            "</tr>" + 
         "</table";

//ES5, / line feed
var str2 = "<table> \
            <tr>  \
                <td>title</td> \
            </tr> \
            </table>";

//ES6
var str3 = `
    <table>
        <tr>
            <td>
            </td>
        </tr>
    </table>
`;
  • In the template string, you can get the value of the variable through ${variable}.
var username = 'jack';
var age = 18;

console.info(`What's your name ${username} , What is your age ${age}`);
  • Create demo04_str.js
var username = "jack";

//Use js to piece together a < Table >
var table = "<table>" + 
            "<tr>" + 
            "<td>"+username+"</td>" + 
            "</tr>" +
            "</table>";

//Template string
var table2 = `
<table>
<tr>
    <td>${username}</td>
    <td></td>
</tr>
<tr>
    <td></td>
    <td></td>
</tr>
</table>
`;

console.info(table)
console.info(table2)

1.3.3 object abbreviation

  • Simplified object writing: omit the attribute value with the same name and omit the function of the method
let name = "Zhang San";
let age = 18;

let person = {                      //ES5 writing method
    name : name,
    age : age,
    getAge : function(){
        return this.age;
    }
}

console.info( JSON.stringify(person));
console.info( person.getAge() );

let person2 = {                     //ES6 writing method
    name,                              //Omit attribute values with the same name
    age,        
    getAge(){                          //Omit function
        return this.age;
    }
}

console.info( JSON.stringify(person2));
console.info( person2.getAge() );

1.3.4 arrow function

  • Arrow function: a concise way to define anonymous functions. (very similar to Lambda expressions in Java)
//Anonymous function
let fn = function(a,b){
    return a + b;
}
console.info( fn(5,10) )    //15

//Basic syntax of arrow function
let fn2 = (a,b) => {
    return a + b;
}
console.info( fn2(5 , 3) )  //8

//Omit 1: parentheses can be omitted when there is only one parameter
// Complete writing
let fn3 = (a) => {
    return a * a;
}
console.info( fn3(5) )      //25

// Ellipsis
let fn32 = a => {
    return a * a;
}
console.info( fn32(5) )   //25

//Omit 2: there is only one bar in the function body, and braces can be omitted. If it is a return statement, the keyword return must be omitted
let fn4 = a => a * a;
console.info( fn4(10) )     //100

// practice
let fn5 = () => console.info("abc");
fn5();          

let fn6 = (a,b,c) => a+b;
console.info( fn6() )       //NaN (Not a number) 

let fn7 = (a,b,c) => a+b;
fn7(3,4,5)

1.3.5 loop traversal in JS

  • For loop traversal: ordinary loop, commonly used to process arrays (for let (I = 0; I < array. Length; I + +) {})

  • map(): array chain operation function (array. Map (FN). Xxx())

  • forEach(): simplify the traversal of arrays, maps and sets (XXX. Foreach (FN))

  • Prepare data

var arr4 = ['x','y','z'];

  • Use of map function

//The map function converts the array to a new array
//var new array = old array. Map (processing function)// Each element in the old array will be processed through the "handler"
//Example: convert array ['a', 'b', 'c'] to string 'cba'
var m = arr4.map( s => {
return s.toUpperCase();
}).reverse().join(",");
console.info(m);

  • Use of forEach function

//forEach traversal
Arr4. Foreach (s = > {/ / traversing the array
console.info(s);
});

2.ES6 advanced

2.1 Advanced Grammar

2.1.1 variable declaration

keywordIs there a variable promotionIs there a temporary deadbandAllow duplicate declarationAllow reassignmentIs it allowed to declare only without assignment
varexistencenon-existentallowallowallow
letnon-existentexistencenot allowallowallow
constnon-existentexistencenot allownot allownot allow
  • Create demo02_var.js
//1. The variable declared by VAR can be promoted
{
    var a = 10;
}
console.info(a);    //10

//2. Repeated declaration is allowed
var b = 20;
var b = 30;
console.info(b);   //30

//3 re assignment is allowed
b = 40;
console.info(b);   //40

//4 only declaration without assignment is allowed
var c;
console.info(c);    //undefined


  • Create demo02_let.js
    • Note: code needs to be run in sequence, and other codes need to be annotated with / * * /. There are running errors.
//1. The variable declared by let is not allowed to be promoted
/*
{
    let a = 10;
}
console.info(a);    //Exception, a is not defined
*/

//2. There is a temporary dead zone: in block code, all variables are local variables (must be declared before use)
/*
var b = 10;
{
    console.info(b);        //b is not defined
    let b = 20;
}
*/

//3. Repeated declaration is not allowed
/*
var c = 10;
let c = 20;     //Identifier 'c' has already been declared  (Variable c (already declared)
*/

/**/
//4 re assignment allowed
let d = 10;
d = 20;
console.info(d);    //20

//5 only declaration without assignment is allowed
let e;
console.info(e);    //undefined

  • Create: demo02_const.js
const a = 10;

//1. Lifting is not allowed
/*
{
    const b = 10;
}
console.info(b)     //b is not defined
*/

//2. There is a temporary dead zone
/*
var c = 10;
{
    console.info(c)     //c is not defined
    const c = 20;
}
*/

//3. Repeated declaration is not allowed
/*
const a = 20;           //Identifier 'a' has already been declared
*/

//4. Re assignment is not allowed
/*
a = 20;             //Assignment to constant variable.
*/

//5. Declaration without assignment is not allowed
//const d;            // Missing initializer in const declaration

2.1.2 deconstruction assignment

  • ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called deconstructing
  • ES5 obtains the syntax of object data as follows:
const people = {
    name: 'lux',
    age: 20
}
const name = people.name;				//ES5 writing method
const age = people.age;
console.log(name + ' ‐‐‐ ' + age)
  • Object deconstruction: resolve multiple attributes from an object to different variables at one time
    • The deconstructed variable name must be consistent with the attribute name.
var person = {
    username : "jack",
    password : "1234",
    "show" : function(){
        console.info("show Yes");
    },
    course : {
        en : 100,
        math : 99
    }
}

//es5 get data
console.info( person.username )
console.info( person.password )
person.show()

//Object deconstruction
let {username,password,show, age } = person;
console.info(username)      //jack
console.info(password)      //1234
console.info( show )        //[Function: show]
console.info( age )         //undefined
show();                     //show executed

//Objects in structure objects
let {course} = person;
console.info(course)    //{ en: 100, math: 99 }
let {course : {en, math}} = person;
console.info(en)        //100

  • Array deconstruction: assign values in order of array sorting
// Declaration array
var arr = ['Jiangsu','Suqian'];

// Deconstruct members from an array
let [province, city] = arr;
console.info(province)
console.info(city)

//Swap 2 variables
let x = 10;
let y = 20;
console.info(`x = ${x} , y = ${y}`);
[y,x] = [x,y];
console.info(`x = ${x} , y = ${y}`);

  • Common applications: traversing Map (explained later)
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world
  • Common applications: module content extraction (explained later)

const { SourceMapConsumer, SourceNode } = require("source-map");

2.1.3 default value of function parameter name

  • When declaring a function parameter, set the default value for the parameter

function log(x, y = 'World') {/ / Y parameter sets the default value
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello

  • Default and Deconstruction

function fun1({x = "x1" , y } = {y : "y2"}){
return [x , y] ;
}
console.info( fun1() ); //[ 'x1', 'y2' ]
console.info( fun1({}) ); //[ 'x1', undefined ] ,
//{} override {Y: "y2"}, deconstruction default, x=x1,y=undefined

  • Default value application: required

console.info(args);
}
fun2();
fun2("abc");

2.1.4 this of arrow function

  • this object:
    • this in the function function represents the current object
    • The arrow function does not have its own this. The this of the arrow function depends on whether there is a function in the outer layer
      1. If yes, this of the outer function is this of the inner arrow function,
      2. If not, in the browser environment, this is window; Specify the environment (for example, vue) in the node.js environment
  • Create demo03_2.js file
var name="external";
var user = {
    name : 'inside',
    show : function(){
        console.info(this.name)
    },
    show2 : () => {
        console.info(this.name) 
        console.info(user.name)
    }
}

user.show()         //inside
user.show2()        //undefined, internal 

  • Create demo03_3.html
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
</body>
</html>
<script>
    var name="external";
    var user = {
        name : 'inside',
        show : function(){
            console.info(this.name)
        },
        show2 : () => {
            console.info(this.name)
            console.info(user.name)
        }
    }
    user.show()         //inside
    user.show2()        //External and internal (on the browser side, this means window)
</script>

2.1.5Map data structure (Map set)

  • JavaScript objects are essentially a collection of key value pairs (Hash structure), but traditionally they can only use strings as keys. This brings great restrictions to its use.
  • ES6 provides a Map data structure. It is similar to an object and a collection of key value pairs, but the scope of "key" is not limited to strings.
var map = new Map([
    ['k1','v1'],
    ['k2','v2']
]);
//Set data
map.set('k3','v3');
console.info(map);      //Map { 'k1' => 'v1', 'k2' => 'v2', 'k3' => 'v3' }

map.set(5,"number key")
console.info(map);      //Map {'K1' = > 'V1', 'K2' = > 'V2', 'K3' = > 'V3', 5 = > 'numeric key'}

//Obtain data
console.info( map.get('k1') );      //v1
console.info( map.get(5) );         //Digital key
console.info( map.get('k100') );   //undefined

//Determine whether the data exists
console.info( map.has('k2') );      //true

//Delete data
map.delete('k2');
console.info(map);             //Map {'K1' = > 'V1', 'K3' = > 'V3', 5 = > 'numeric key'}

//Traversal data
map.forEach( (k,v) => {
    console.info(`Key is ${k},Value is ${v}`)
});

2.1.6 Set data structure (Set)

  • ES6 provides a new data structure Set. It is similar to an array, but the values of members are unique and there are no duplicate values.
//Set: store unique data
var set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(2);
set.add(1);

console.info( set );        //Set { 1, 2, 3 }

  • Filter duplicate data in the array
var arr = [2, 3, 5, 4, 5, 2, 2];

//Mode 1
var set2 = new Set();
// 1) Traverse the array and add data to the set
arr.map( s => set2.add(s) );
// 2) Traverse the set collection and add it to the new array
var arr2 = [];
set2.forEach( v => arr2.push(v) );
console.info( arr2 );       //[ 2, 3, 5, 4 ]

//Mode 2
var arr3 = [ ... new Set(arr) ]
console.info( arr3 );       //[ 2, 3, 5, 4 ]

2.1.7 for... of traversal

  • In JavaScript, there are many kinds of data traversal. for... Of is provided in ES6 to unify the traversal of all data structures
//Prepare data
var arr4 = ['x','y','z'];

var map4 = new Map();
map4.set("a","1111");
map4.set("b","2222");
map4.set("c","3333");

var set4 = new Set();
set4.add("m");
set4.add("n");
set4.add("L");

var obj4 = {
    name : "jack",
    password : "1234"
}
  • for... of traversal
// for ... of 
for(let a of arr4){           //Traversal array
    console.info(a);
}
for(let [k,v] of map4){      //Traversing Map, for... of and Deconstruction
    console.info(`The output data key is ${k}Value is ${v}`);
}
for(let s of set4){          //Traversal Set
    console.info(s);
}
for(let key of Object.keys(obj4)){   	//Custom objects cannot be traversed. They need to be converted into "key array" with the help of keys
    console.info(`The key of the object is ${key},Value is ${obj4[key]}`);
}
for(let [k,v] of Object.entries(obj4)){//It can also be converted into "key value pairs" with the help of entries
    console.info(`entries : The key of the object is ${k},Value is ${v}`);
}

//Supplement: custom objects can also be traversed through special processing ([Symbol.iterator]), but there are bug s and imperfections. Refer to the following:
let obj = {
	//Original content
	length: 3,
	[Symbol.iterator]: Array.prototype[Symbol.iterator]
}
  • Existing traversal in JS
Traversal modedescribeexample
for loop traversalOrdinary loop, often used to deal with arraysfor (let i = 0;i < array.length;i++){
map()Array chained operatorarray.map( fn ).xxx()
forEach()Simplify traversal of arrays, maps and setsxxx.forEach( fn )
for...inTraverse the enumerable properties of an object in any orderfor(let xx in obj) {}
for...ofDifferent data structures provide a unified access mechanismfor(let xx of obj) {}
  • Use of map function
//The map function converts the array to a new array  
//var new array = old array. Map (processing function); 		// Each element in the old array will be processed through the "handler"
//Example: convert array ['a','b','c '] to string' cba '
var m = arr4.map( s => {
    return s.toUpperCase();
}).reverse().join(",");
console.info(m);

  • Use of forEach function
//forEach traversal
arr4.forEach(s => {         //Traversal array
    console.info(s);
});
map4.forEach( (k,v)=> {     //Traverse Map
    console.info(`${k} ${v}`);
});
set4.forEach( k => {        //Traversal Set
    console.info( k ) ;
});
//obj4.forEach();           // I won't support it
  • for... in traversal object
for(let prop in obj4){
    console.info( prop  + "," + obj4[prop]);
}

2.1.8 rest parameters (formal parameters...)

  • The rest parameter is the variable parameter of JS. Use "..." before the last variable in the formal parameter list
    Function name (parameter 1, parameter 2,... Variable)
function add(...num){               	//The variable parameter num is an array that stores all the arguments at run time
    var sum = 0 ;
    num.forEach( i => sum += i);
    return sum;
}
console.info( add(1,2,3) );

function count(args,...other){
    console.info(arguments.length);     //Although the number of parameters is a pseudo array, forEach cannot be used for traversal
    console.info(other.length);         //The number of variable parameters, the true array, can be traversed by forEach
}
count(1,2,3);

2.1.9 extension operators (arguments...)

  • The spread operator is three dots (...). It is like the inverse operation of the rest parameter

    • The operation data is an array, which is converted into a comma separated sequence of parameters.
    • The operation data is an object. Take out all traversable properties of the parameter object and copy them to the current object
var arr = ['a','b','c'];
function fun3(x,y,z){
    console.info( [x,y,z] );
}

fun3( arr );        //[ [ 'a', 'b', 'c' ], undefined, undefined ]
fun3( ...arr );     //[ 'a', 'b', 'c' ]

let z = { a: 3, b: 4 };
let n = { ...z }; // { a: 3, b: 4 }

  • Apply: merge arrays

var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e'];
//Merge through concat function
console.info( arr1.concat(arr2 ,arr3 ) );
//Merge by extension operator
console.info( [...arr1 ,...arr2 ,...arr3] );

  • Applying: String splitting

//Split string by split
console.info( "abc".split("") );
//Split by extension operator
console.info( [..."abc"] );

2.2 modularization

  • Before ES6, JavaScript had no module system, so it was impossible to split a large program into interdependent small files and assemble them in a simple way.

  • Before ES6, the community provided some solutions, the most important of which are CommonJS and AMD

    • CommonJS, static optimization, for server.
      • Module reference: https://blog.csdn.net/arsaycode/article/details/78959780
    • AMD has two types, which are loaded at runtime and used for browsers.
      • AMD reference: https://efe.baidu.com/blog/dissecting-amd-what/

2.2.1 Es5 commonjs solution

  • CommonJS is a server-side solution (commonsJs can run in node.js)
  • CommonJS needs a compatible script loader to support the require and module.exports functions for module import and export.
  • Node.js supports this idea
  • Module export

module.exports = (a,b)=> a+b;

  • Module import

let add = require("./demo07_1");
console.info( add(1,2) );

  • function

  • require operation analysis

When the Node encounters require(X), it is processed in the following order.
(1) If X is a built-in module (such as require('http '))
a. return to the module.
b. no further implementation.
(2) If X starts with '. /' or '/' or '... /'
a. determine the absolute path of X according to the parent module of X.
b. take X as a file and look for the following files in turn. As long as one of them exists, return the file and do not continue.
X
X.js
X.json
X.node
c. take X as a directory and look for the following files in turn. As long as one of them exists, return the file and do not continue.
X/package.json (main field)
X/index.js
X/index.json
X/index.node
(3) If X does not have a path
a. determine the possible installation directory of X according to the parent module of X.
b. in each directory in turn, load X as a file name or directory name.
(4) Throw "not found"

  • Special usage: execute functions while importing

2.2.2ES6 module implicit requirements

  • The module of ES6 automatically adopts strict mode, whether you add "use strict" to the module header or not;.
  • Strict mode mainly has the following limitations.

Variables must be declared before use
The parameter of the function cannot have an attribute with the same name, otherwise an error will be reported
The with statement cannot be used
You cannot assign a value to the read-only attribute, otherwise an error will be reported
The prefix 0 cannot be used to represent octal numbers, otherwise an error will be reported
You cannot delete the undeletable attribute, otherwise an error will be reported
The variable delete prop cannot be deleted and an error will be reported. Only the attribute delete global[prop] can be deleted
eval does not introduce variables into its outer scope
eval and arguments cannot be reassigned
arguments does not automatically reflect changes in function parameters
arguments.callee cannot be used
arguments.caller cannot be used
Prohibit this from pointing to global objects
You cannot use fn.caller and fn.arguments to get the stack of function calls
Added reserved words (such as protected, static and interface)

2.2.3ES6 module

  • A module is a file that exposes its properties or methods to other modules.

    • The ES6 module is mainly composed of two commands: export and import.
    • Export command: Specifies the external interface of the module. An export statement can be declared once, and there can be multiple in a file.
    • Import command: import other modules.
  • export external declaration member

//Writing 1: declare a member
export var m = 1;
//Writing method 2: batch declaration of members
var m = 1;
export {m};
//Writing method 3: alias when declaring members
var n = 1;
export {n as m};

  • Import import module

//Method 1: use members of other modules
import {member} from 'module';
//Method 2: alias members when importing modules
import {member as alias} from 'module';
//Method 3: import all
Import {* as alias} from 'module';

  • Node.js demo [Note: the extension is mjs]
    • The early version of Node.js does not support export/import. It is supported after version 9, but special processing is required.
  • Step 1: write demo08_1.mjs file

var username = 'jack';
function getName(){
return username;
}
export { username , getName }

  • Step 2: write demo08_2.mjs file, import demo02_1 module

import {username,getName} from './demo08_1';
console.info( username );
console.info( getName() );

  • Step 3: run with node

node --experimental-modules .\demo08_2.mjs

  • If the mjs file is not used and the parameter -- experimental modules is not added during execution, the following exception will occur:

2.2.4 export default

  • When using the import command to load a module, you must know the variable name or function name in the module, otherwise it cannot be loaded.
  • For ease of use, the module allows you to define the default output using export default. Only one is allowed for a module
  • Default output.
    • Default export variable
    • Write es6_part1.mjs, declaring variables

var sum = 100;
export default sum;

  • Write es6_part2.mjs, custom variable name

import demo from './es6_part1';
console.info( demo ); //demo is the variable name

  • Default export function
    • Write es6_part1.mjs, declaration function

function show(){
return "abc";
}
export default show;

  • Write es6_part2.mjs, custom function name

import demo from './es6_part1';
console.info( demo() ); //demo is the function name, which must be called with ()

  • The default is used in conjunction with other exported content
    • export

export default is the default export content;
export {other member list};

  • Import
    import by default, {other member list} from module;

  • Extended content:
    • In essence, export default is to output a variable or function name called default. Renaming is allowed during import.
  • export

function add(x, y) {
return x * y;
}
//Method 1: default export
//export default add;
//Method 2: normal export, rename the variable name to default. Same as "mode 1"
export {add as default};

  • Import

//Method 1: default import
import xxx from 'module';
//Method 2: import normally, and rename the variable name default to xxx, which is the same as "method 1"
Import {default as XXX} from 'module';

3.ajax usage

3.1 pre Technology: Promise object

  • Promise is a solution to asynchronous programming

  • Promise object completes asynchronous programming with synchronous operation.

  • More reasonable and powerful than traditional solutions -- callback functions and events

  • Asynchronous operation demonstration

console.info("1. Before asynchronous execution");
setTimeout(function(){
console.info("2. Asynchronously executing");
} , 1000);
console.info("3. After asynchronous execution");
/*The output results are as follows: (the second item will be executed in 1 second)
1. Before asynchronous execution
3. After asynchronous execution
2. Asynchronous execution
*/

  • Promise demo

console.info("1. Before asynchronous execution");
new Promise( (resolve) => {
setTimeout(function(){
console.info("2. Asynchronously executing");
resolve(); // Successful execution
});
}).then( () => {
console.info("3. After asynchronous execution");
});
/*The output results are as follows:
1. Before asynchronous execution
2. Asynchronous execution
3. After asynchronous execution
*/

  • Basic grammar
    • After that, the object using Promise has been created. We just need to write then.

new Promise( (resolve, reject) => {
If (asynchronous operation succeeded){
Resolve (success parameter); / / fixed content, executed when successful
}
}).then( (res) => {
//After the asynchronous operation is successfully executed, the then block is executed.
})
;

  • Advanced Grammar

new Promise( (resolve, reject) => {
If (asynchronous operation succeeded){
Resolve (success parameter); / / fixed content, executed when successful
} else {
Reject (failure parameter); / / fixed content, executed in case of failure
});
}).then( (res) => {
//After the asynchronous operation is successfully executed, the then block is executed.
}).catch( (res ) => {
//After the asynchronous operation fails, the catch block is executed
});

  • Application: axios handling ajax

3.2axios module usage

3.2.1 general

  • What is axios?
    • Axios, a Promise based HTTP client, can work in the browser or in node.js.
    • Official website: http://www.axios-js.com/
  • function
    • Create XMLHttpRequest from browser
    • Create http request from node.js
    • Promise API supported
    • Intercept requests and responses
    • Transform request and response data
    • Cancel request
    • Automatically convert JSON data
    • Client support prevents XSRF attacks

3.2.2 sending various requests

  • GET request
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="js/axios.js"></script>
    <script>
        // axios.get("request path"). Then (success function). Catch (failure function)
        var url = "http://data.javaliang.com/data/jack/student"
        axios.get(url)
        .then(function (response) {
            // Query results
            response.data.data.forEach(student => {
                console.info(student)
            });
            console.info(response)
        })
        .catch(function (error) {
            console.info(error)
        })
    </script>
</head>
<body>
    
</body>
</html>
  • POST request
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="js/axios.js"></script>
    <script>
        // axios.post("request path", parameter object). Then (success function). Catch (failure function)
        var url = "http://data.javaliang.com/data/jack/student"
        var obj = {
            "id":"s001",
            "name":"Zhang San",
            "age":"18",
            "sex":"male",
        }
        axios.post(url, obj)
        .then(function (response) {
            // Query results
            console.info(response.data)
        })
        .catch(function (error) {
            console.info(error)
        })
    </script>
</head>
<body>
    
</body>
</html>
  • put request
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="js/axios.js"></script>
    <script>
        // axios.put("request path", parameter object). Then (success function). Catch (failure function)
        var url = "http://data.javaliang.com/data/jack/student"
        var obj = {
            "id":"s001",
            "name":"Zhang San 33",
            "age":"182",
            "sex":"male",
        }
        axios.put(url, obj)
        .then(function (response) {
            // Query results
            console.info(response.data)
        })
        .catch(function (error) {
            console.info(error)
        })
    </script>
</head>
<body>
    
</body>
</html>
  • delete request
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="js/axios.js"></script>
    <script>
        // axios.put("request path", parameter object). Then (success function). Catch (failure function)
        var url = "http://data.javaliang.com/data/jack/student/s001"
        axios.delete(url)
        .then(function (response) {
            // Query results
            console.info(response.data)
        })
        .catch(function (error) {
            console.info(error)
        })
    </script>
</head>
<body>
    
</body>
</html>

3.2.3 asynchronous writing of sync (es8)

async function function name (){
let response = await axios.get('request path ')
}

  • GET request
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="js/axios.js"></script>
    <script>
        /*
            async function Function name (){
                let response = await axios.get('Request path ')
            }
        */
        async function findAll() {
            var url = "http://data.javaliang.com/data/jack/student"
            let { data } = await axios.get(url)
            // Traversal data
            data.data.forEach(student => {
                console.info(student)
            });
        }
        findAll()

    </script>
</head>
<body>
    
</body>
</html>
  • POST request
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="js/axios.js"></script>
    <script>

        /*
            async function Function name (){
                let response = await axios.post('Request path ', parameter object)
            }
        */
        async function save() {
            var url = "http://data.javaliang.com/data/jack/student"
            var obj = {
                "id":"s002",
                "name":"Zhang San",
                "age":"18",
                "sex":"male",
            }
            let { data } = await axios.post(url, obj)
            console.info(data)
        }
        save()


    </script>
</head>
<body>
    
</body>
</html>
  • PUT request
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="js/axios.js"></script>
    <script>

        /*
            async function Function name (){
                let response = await axios.put('Request path ', parameter object)
            }
        */
        async function update() {
            var url = "http://data.javaliang.com/data/jack/student"
            var obj = {
                "id":"s002",
                "name":"Zhang San",
                "age":"18",
                "sex":"male",
            }
            let { data } = await axios.put(url, obj)
            console.info(data)
        }
        update()

    </script>
</head>
<body>
    
</body>
</html>
  • DELETE request
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="js/axios.js"></script>
    <script>
        /*
            async function Function name (){
                let response = await axios.delete('Request path ', parameter object)
            }
        */
        async function del() {
            var url = "http://data.javaliang.com/data/jack/student/s001"
            let { data } = await axios.delete(url)
            console.info(data)
        }
        del()

    </script>
</head>
<body>
    
</body>
</html>

3.3 use in node

3.3.1 installation

Another note on the installation tutorial of Node.js~

3.3.2 sending various requests

  • Import the axios module and set the base item

//1. Import axios module
const axios = require('axios')
//2. Set basic item
//2.1 determining the base address of the back-end server
axios.defaults.baseURL = 'http://localhost:8080';

  • Send get request

//1. Import axios module
const axios = require('axios')
//2. Set basic item
//2.1 determining the base address of the back-end server
axios.defaults.baseURL = 'http://localhost:8080';
//3. Send get request
axios.get('/test')
.then(function (response) {
console.info('get request succeeded ')
//console.info(response)
})
.catch(function (error) {
console.info('get request failed ')
//console.info(error)
})

  • Send post request

//4 send post request
//4.1 preparation of request data
let user = {
username:'jack',
password:'1234'
}
//4.2 send post request
axios.post('/test', user)
.then(function (response) {
//1) Response status code
console.info(response.status)
//2) Response data
console.info(response.data)
})
.catch(function (error) {
console.info('post request failed ')
})

  • Send put request

//5 send put request
axios.put('/test/100', user)
.then(function (response) {
console.info(response.status)
})
.catch(function (error) {
console.info('put request failed ')
console.info(error)
})

  • Send delete request

//6 send delete request
axios.delete('/test/100')
.then(function (response) {
console.info(response.data)
})
.catch(function (error) {
console.info('delete request failed ')
})

3.3.3 asynchronous writing of sync (es8)

  • Promise uses the then function to make chain calls, and the writing style is "left to right".

  • ES8 provides async/await to change the asynchronous writing style from top to bottom, like writing synchronous code to complete asynchronous operations.

    • Features: async must modify the outer calling function, and await must modify the asynchronous function (i.e. Promise)
  • Overwrite get request

//3. Send get request
async function findAll () {
let {status,data} = await axios.get('/test');
console.info(${status} , ${data})
}
findAll();

  • Overwrite post request

//4 send post request
//4.1 preparation of request data
let user = {
username:'jack',
password:'1234'
}
//4.2 send post request
async function save(){
let {data} = await axios.post('/test', user);
console.info( data )
}
save();

  • Overwrite put request

//5 send put request
async function update(){
let {status} = await axios.put('/test/100', user);
console.info(status)
}
update();

  • Overwrite delete request

//6 send delete request
async function deleteDemo(){
let {data} = await axios.delete('/test/100');
console.info(data)
}
deleteDemo();

3.3.4 interceptor

  • request interceptor

//2.2 request / response interceptor
axios.interceptors.request.use( config => {
config.headers.Authorization = 'custom content';
return config;
}, error => {
return Promise.reject(error);
});

  • Modify controller

@GetMapping
public ResponseEntity findAll(HttpServletRequest request){
String authorization = request.getHeader("Authorization");
return ResponseEntity.ok("query all:" + authorization);
}

  • test

//3. Send get request
async function findAll () {
let {status,data} = await axios.get('/test');
console.info(${status} , ${data})
}
findAll();

Have you practiced adding, deleting, changing and checking~
Ready to learn Vue
Squat down, my Vue~

Topics: Javascript ECMAScript Vue