4: Front and back interaction of Vue

Keywords: axios Javascript JSON JQuery

1: Overview

1 interface call mode

Native ajax
 ajax based on jQuery
fetch
axios

2: Traditional URL

Format: Schema: / / lost: port / path? Query fragment
 1):schema: protocol. For example, http,https,ftp, etc
 2);host: domain name or IP address
 3):port: port, http default port 80, can be omitted
 4):path: path. For example / a B C / A / B / B / C
 5):query: query parameters, such as uname = Lisi & age = 12
 6):fragment: hash, used to locate a location.

3: URL address format - URL in Restful form

HTTP request mode
 1):GET query
 2):POST add
 3):PUT modification
 4):DELETE delete

Rule compliant URL address

1):http://www.hello.com/books GET
2):http://www.hello.com/books POST
3):http://www.hello.com/books/123 put
4):http://www.hello.com/books/123 DELETE

Two: Promise usage

Asynchronous call

Asynchronous effect analysis

1: Scheduled tasks
2:AJAX
 3: Event function

Dependency analysis of multiple asynchronous calls:

1: The result order of multiple asynchronous calls is uncertain.
2: Asynchronous call results need to be nested if there is a dependency.

Promise overview

Promise is a solution of asynchronous programming. Syntactically, promise is an object from which messages of asynchronous operations can be obtained.
The main advantages of using Promise are as follows:

Multiple nesting problems can be avoided (callback to hell)
Promise object provides concise API, which makes it easier to control asynchronous operation

Promise overview

Instantiate the Promise object, pass the function in the constructor, which is used to handle asynchronous tasks.
Two parameters, resolve and reject, are used to handle success and failure, and obtain the processing results through p.then.

var p =new Promise(function(resolve,reject){
	//Call resolve() on success
	//Call reject() on failure
});
p.then(function(ret){
	//Get normal results from resolve.
},function(ret){
	//Get error message from reject
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>Front and back interaction</div>
<script type="text/javascript">
    /*
        Front and back interaction - asynchronous programming and Promise overview.
    */
    var p= new Promise(function (resolve,reject) {
        //This is used to implement asynchronous tasks.
        setTimeout(function () {
            var flag=true;
            if(flag){
                //Normal condition
                resolve('hello');
            }else{
                //Abnormal situation
                reject('Error');
            }
        },100);
    });
    p.then(function (data) {
        console.log(data);
    },function (info) {
        console.log(info)
    })
</script>
</body>
</html>

Processing Ajax requests based on Promise

1. Handle native Ajax

function queryData(){
	return new Promise(function(resolve,reject){
		var xhr=new XMLHttpRequest();
		xhr.onreadystatechange=function(){
			if xhr.readyState!=4) return ;
			if(xhr .status ==200){
				resolve(xhr.responseText)
				}else{
					reject('Error');
				}
			}
			xhr.open('get','/data');
			xhr.send(null);
			}}
			}

2: Function return value in the then parameter
1. Return Promise instance object
The returned instance object calls the next then
2: Return normal value
The normal value returned is passed directly to the next then and received through the parameter in the then parameter.

API s commonly used by Promise

1: Instance method

p.then get the right results for asynchronous tasks
 p.catch() gets exception information
 p.finally() will be executed successfully or not (it is not a formal standard yet)
queryData()
.then(function(data){
	console.log(data);
})
.catch(function(data){
	console.log(data);
})
.finally(function(){
	console.log('finished');
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>Front and back interaction</div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
    function foo() {
        return new Promise(function (resolve, reject) {
          setTimeout(function () {
              //resolve(123);
              reject('error');
          },100);
        });
    }
   /* foo()
        .then(function (data) {
            console.log(data);
        })
        .catch(function (data) {
            console.log(data);
        })
        .finally(function () {
            console.log('finished');
        });*/
    foo()
        .then(function (data) {
            console.log(data);
        },function (data) {
            console.log(data);
        })
        .finally(function () {
            console.log('finished');
        })
</script>
</body>
</html>

6: API s commonly used by promise
Object method

Promise.all() processes multiple asynchronous tasks concurrently, so the results can only be obtained after all tasks are completed
 Promise.race() processes multiple asynchronous tasks concurrently, and the result can be obtained as long as one task is completed.
Promise.all([p1,p2,p3]).then((result =>{
	console.log(result)
})
Promise.race([p1,p2,p3]).then((result =>{
	console.log(result)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
    function queryData(url) {
        return new Promise(function(resolve, reject){
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if(xhr.readyState != 4) return;
                if(xhr.readyState == 4 && xhr.status == 200) {
                    // Deal with normal conditions
                    resolve(xhr.responseText);
                }else{
                    // Handling exceptions
                    reject('Server error');
                }
            };
            xhr.open('get', url);
            xhr.send(null);
        });
    }
    var p1=queryData('http://localhost:3000/a1');
    var p2=queryData('http://localhost:3000/a2');
    var p3=queryData('http://localhost:3000/a3');
    Promise.all([p1,p2,p3]).then(function (result) {
        console.log(result);
        console.log('sss');
    });
</script>
</body>
</html>

Interface call fetch usage

Basic characteristics:
A simpler way to obtain data, with more powerful and flexible functions, can be regarded as an upgraded version of xhr.
Implementation based on Promise

Grammatical structure
fetch(url).then(fn2)
			.then(fn3)
			...
			.catch(fn)
Basic usage:
fetch('/abc').then(data=>{
	return data.text();
}).then(ret=>{
	//Note that this is the final data.
	console.log(ret);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    /*
        fetch API Basic Usage
    */
    fetch('http://localhost:3000/fdata').then(function (data) {
        //The text() method is part of the fetchAPI and returns a Promise instance object. Used to get the data acquired in the background.
        return data.text();
    }).then(function (data) {
        console.log(data);
    })
</script>
</body>
</html>

fetch request parameters

1.fetch Request parameters
method(String):HTTP Request method, default toGET(GET,POST,PUT,DELETE)
body(String):HTTP Request parameters for
headers(Object):HTTP Request header of, default to{}

```cpp
fetch('/abc',{
	method:'get'
}).then(data =>{
	return data.text();
}).then(ret=>{
	//Note that this is the final data
	console.log(ret);
	});
GET Parameter passing in request mode
fetch('/abc?id=123').then(data=>{
	return data.text();
}).then(ret=>{
	//Note that this is the final data.
	console.log(ret)
	})
//perhaps
fetch('/abc/123').then(data=>{
	return data.text();
}).then(ret=>{
	//Note that this is the final data.
	console.log(ret)
	})
fetch('/abc?id=123',{
	method:'delete'
}).then(data=>{
	return data.text();
}).then(ret=>{
	//Note that this is the final data.
	console.log(ret)
	})

Parameter passing of POST request mode

fetch('/books',{
	methods:'post',
	body:'uname=list&pwd=123',
	headers:{
		'Content-Type':'application/x-www-form-urlencoded',
	}
}),then(data=>{
	return data.text();
}).then(ret=>{
	console.log(ret);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    /*
        fetch API Basic Usage
    */
/*
   fetch('http://localhost:3000/books',{
        method:'post',
        body:'uname=lisi&pwd=123',
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    }).then(function (data) {
        //text()Method is part of the fetchAPI and returns a Promise instance object. Used to get the data acquired in the background.
        return data.text();
    }).then(function (data) {
        console.log(data);
    })
*/

    fetch('http://localhost:3000/books',{
        method: 'post',
        body: JSON.stringify({
            uname: 'Zhang San',
            pwd: '456'
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(function(data){
            return data.text();
        }).then(function(data){
        console.log(data)
    });
</script>
</body>
</html>

Parameter passing of PUT request mode

fetch('/books',{
	methods:'put',
	body:JSON.stringify({
	uname:'lisi',
	age:12
	})
	headers:{
		'Content-Type':'application/json',
	}
}),then(data=>{
	return data.text();
}).then(ret=>{
	console.log(ret);
});

fetch response results

Response data format

text(); handle return body as string type
 JSON: the returned result is the same as JSON.parse(responseText).
fetch('/abc' then(data=>{
	//return data.text();
	return data.json();
}).then(ret=>{
	console.log(ret);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    /*
        fetch API Basic Usage
    */
    fetch('http://localhost:3000/json').then(function (data) {
        return data.json()
    }).then(function (data) {
        console.log(data);
    })
</script>
</body>
</html>

2: Basic usage of Axios

Interface call - axios usage

1. Basic characteristics of Axios
axios: is an HTTP client based on Promise for browsers and node.js.
It has the following characteristics:

Support browser and node.js
 promise support
 Ability to intercept requests and responses
 It can automatically convert JSON data.
```cpp
axios.get('/data')
	.then(ret =>{
		//The data attribute has a fixed name, which is used to get the data of the background response.
		console.log(ret.data)
		}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    axios.get('http://localhost:3000/adata').then(function (ret) {
        //z note that the daa attribute is a fixed use to get the actual data in the background.
        console.log(ret);
    })
</script>
</body>
</html>

3: Common API of Axios

get: query data
 post: add data
 put: modify data
 Delete: delete data

Parameter passing of axios.
get pass through parameters

Get pass parameters
	Pass parameters through URL
	Pass the parameters through the params option.
Method 1:
axios.get('/adata?id=123')
	.then(ret=>{
		console.log(ret.data)
})
Method two:
axios.get('/adata/123')
	.then(ret=>{
		console.log(ret.data)
})
Method3:
axios.get('/adata',{
	params:{
		id:123
	}
})
.then(ret=>{
	console.log(ret.data)
})

2.DELETE passing parameters

axios.delete('/adata?id=123)
	.then(ret=>{
		console.log(ret.data)
})
axios.delete('/adata/123)
	.then(ret=>{
		console.log(ret.data)
})
axios.delete('/adata',{
	params:{
		id:123
	}
}).then(ret=>{
	console.log(ret.data)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">

axios.delete('http://localhost:3000/axios',{
    params:{
        id:111
    }
}).then(function (ret) {
    console.log(ret.data)
})

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

3. POST transfer parameters of Axios
Pass parameters through options: (json data is passed by default)

axios.post('/adata',{
	uname:'tome',
	pwd:123
}).then(ret=>{
	console.log(ret.data)
})
adopt URLSerchParams Transfer parameters(application/x-www-form-urlencoded)
const params=new URLSerchParams();
params.append('patam1','value1');
params.append('param2','value2');
axios.post('/api/test',params).then(ret=>{
	console.log(ret.data)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    var params=new URLSearchParams();
    params.append('uname','zhangsan');
    params.append('pwd','123');
    axios.post('http://localhost:3000/axios',params).then(function (ret) {
        console.log(ret.data);
    })
</script>
</body>
</html>

4:PUT pass parameters

axios.put('/adata/123',{
	uname:'tom,
	pwd:123
}).then(ret=>{
	console.log(ret.data)
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
  axios.put('http://localhost:3000/axios/123',{
      uname:'lisi',
      pwd:123
  }).then(function (ret) {
      console.log(ret.data)
  })
</script>
</body>
</html>

axios response results

1: Main properties of response results

Data: data returned from the actual response 
headers: response header information
 Status: response status code
 statusText: response status information

Global configuration of axios

axios.defaults.timeout=3000;//Timeout time
axios.defaults.baseURL='http:localhost:3000/app';//Default address
axios.defaults.headers['mytoken'] = 'aqwerwqwerqer2wrwe23eresdf23'//Set request header.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
        axios Global configuration for
    */
    //Configure the default base URL address for the request
    axios.defaults.baseURL='http://localhost:3000/';
    //Configure request header information
    axios.defaults.headers['mytoken']='hello';
    axios.get('axios-json').then(function (ret) {
        console.log(ret);
    })

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

axios interceptor

1: Request interceptor
Set some information before the request is sent.

code implementation

//Add a request interceptor
axios.interceptors.request.use(function(config){
	//Set some information before the request is sent
	return config;
},function(err){
	//Processing error messages for responses
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
        axios Interceptor
    */
    axios.interceptors.request.use(function (config) {
        console.log(config.url);
        //Interceptor configuration request header
        config.headers.mytoken='nihao';
        return config;
    },function (err) {
        console.log(err);
    });

    axios.get('http://localhost:3000/adata').then(function (ret) {
        console.log(ret)
    });

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

2: Response interceptor
Before obtaining the data, some processing is done to the data.

//Add a response interceptor
axios.interceptors.response.use(function(res){
	//The returned data is processed here
	return res;
},function(err){
//Processing error messages for responses
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
        axios Interceptor
    */
    axios.interceptors.request.use(function (config) {
        console.log(config.url);
        //Interceptor configuration request header
        config.headers.mytoken='nihao';
        return config;
    },function (err) {
        console.log(err);
    });
    axios.interceptors.response.use(function (res) {
        console.log(res);;
        var data=res.data;
        return data;
    },function (err) {
        console.log(err);
    });
    axios.get('http://localhost:3000/adata').then(function (ret) {
        console.log(ret)
    });

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


Interface calls async and await usage

async/await is a new syntax introduced by ES7, which is more convenient for asynchronous operation.
Async keyword is used on function (the return value of async function is Promise instance object)
Await keyword is used in async functions (await can get asynchronous results)

async function queryData(id){
	Const ret=await axios.get('/data');
	return ret;
}
queryData.then(ret=>{
	console.log(ret)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
      async/await To process asynchronous operations:
      async Function returns a Promise instance object
      await You can directly follow a Promise instance object
    */
    axios.defaults.baseURL = 'http:localhost:3000';
    // axios.get('adata').then(function(ret){
    //   console.log(ret.data)
    // })

 /*   async function queryData() {
        var ret = await axios.get('adata');
        console.log(ret.data)
        //return ret.data;
    }*/

     async function queryData() {
       var ret = await new Promise(function(resolve, reject){
         setTimeout(function(){
           resolve('nihao')
         },1000);
       })
       // console.log(ret.data)
       return ret;
     }
     queryData().then(function(data){
       console.log(data)
     })
</script>
</body>
</html>

Interface calls async and await to handle multiple asynchronous requests

Scenarios with multiple requests

async function queryData(id){
	const info await axios.get('/async1');
	const ret=await axios.get('async2?info='+info.data);
	return ret;
}
queryData.then(ret=>{
	console.log(ret)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
    /*
        async/await Processing multiple asynchronous tasks
    */
    axios.defaults.baseURL='http://localhost:3000';
    async function queryData() {
        var info = await axios.get('async1');
        var ret = await axios.get('async2?info=' + info.data);
        return ret.data;
    }
    queryData().then(function(data){
        console.log(data)
    })
</script>
</body>
</html>
156 original articles published, praised 16, visited 40000+
Private letter follow

Posted by viveleroi0 on Mon, 09 Mar 2020 21:59:10 -0700