Interface calling mode
- Native ajax
- ajax based on jQuery
- fetch
- axios
1.Promise
- Promise is simply a container that holds the results of an event (usually an asynchronous operation) that will not end in the future. Syntactically speaking, promise is an object from which you can get the message of asynchronous operation.
- It mainly solves the problem of asynchronous deep nesting.
- promise provides a concise API that makes asynchronous operations easier.
1.1 send Ajax request based on Promise
<script type="text/javascript"> /* Send Ajax request based on Promise */ function queryData(url) { # 1.1 create a Promise instance var p = new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState != 4) return; if(xhr.readyState == 4 && xhr.status == 200) { # 1.2 handling normal conditions resolve(xhr.responseText); }else{ # 1.3 handling exceptions reject('Server error'); } }; xhr.open('get', url); xhr.send(null); }); return p; } # Note: you need to start a service here # In the then method, you can also directly return data instead of Promise object, and you can receive data in the later then queryData('http://localhost:3000/data') .then(function(data){ console.log(data) # 1.4 return is required to continue chain programming return queryData('http://localhost:3000/data1'); }) .then(function(data){ console.log(data); return queryData('http://localhost:3000/data2'); }) .then(function(data){ console.log(data) }); </script>
1.2 Promise basic API
1.2.1 example method
.then()
- Get the correct results for asynchronous tasks
.catch()
- Get exception information
.finally()
- Success or failure will be implemented (not a formal standard)
<script type="text/javascript"> /* Promise Common API instance methods */ // console.dir(Promise); 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') // }); // -------------------------- // The two expressions are equivalent foo() .then(function(data){ # Get the correct results for asynchronous tasks console.log(data) },function(data){ # Get exception information console.log(data) }) # Success or failure will be implemented (not a formal standard) .finally(function(){ console.log('finished') }); </script>
1.2.2 static method
.all()
- Promise. The all method accepts an array as a parameter, and the objects in the array (p1, p2, p3) are promise instances (if it is not a promise, this item will be converted to a promise with Promise.resolve). Its state is determined by these three promise instances
.race()
- Promise. The race method also accepts an array as an argument. When the state of one instance in p1, p2 and p3 changes (becomes fully or rejected), the state of p changes accordingly. And pass the return value of the promise that changes the state first to the callback function of p
<script type="text/javascript"> /* Promise Common API object methods */ // console.dir(Promise) 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) { // Handle 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){ // The parameters [p1,p2,p3] in all correspond to the returned results one by one ["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"] console.log(result) //["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"] }) Promise.race([p1,p2,p3]).then(function(result){ // Since P1 executes faster, Promise's then() will get the result 'P1'. P2 and P3 are still executing, but the execution results will be discarded. console.log(result) // "HELLO TOM" }) </script>
2.fetch
- Fetch API is a new ajax solution. Fetch returns Promise
- fetch is not a further encapsulation of ajax, but a native js without the XMLHttpRequest object.
- fetch(url, options).then()
<script type="text/javascript"> /* Fetch API Basic Usage fetch(url).then() The path Fetch of the first parameter request will return Promise, so we can use then to get the successful result of the request */ fetch('http://localhost:3000/fdata').then(function(data){ // The text() method is part of the fetch API. It returns a Promise instance object to get the data returned in the background return data.text(); }).then(function(data){ // In this then, we can get the final data console.log(data); }) </script>
2.1 HTTP request in fetch API
- fetch(url, options).then()
- HTTP protocol, which provides us with many methods, such as POST, GET, DELETE, UPDATE, PATCH and PUT
- The default is GET request
- You need to specify the corresponding method in the options object. Method: the requested method
- For post and normal requests, you need to set the request header headers and body in options
<script type="text/javascript"> /* Fetch API Call interface to pass parameters */ #1.1 GET parameter passing - traditional URL through URL? Formal parameters fetch('http://localhost:3000/books?id=123', { # GET requests can be omitted without writing. The default is GET method: 'get' }) .then(function(data) { # It returns a Promise instance object, which is used to get the data returned in the background return data.text(); }).then(function(data) { # In this then, we can get the final data console.log(data) }); #1.2 the get parameter passes the URL in restful form, and the parameter is passed in / form, i.e. id = 456, which is related to the configuration of the ID background fetch('http://localhost:3000/books/456', { # GET requests can be omitted without writing. The default is GET method: 'get' }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); #2.1 the delete request method parameter is id=789 fetch('http://localhost:3000/books/789', { method: 'delete' }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); #3 POST request parameter transfer fetch('http://localhost:3000/books', { method: 'post', # 3.1 data transmission body: 'uname=lisi&pwd=123', # 3.2 setting request header headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # POST request parameter transfer 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) }); # The parameter modification id of the PUT request is 123 fetch('http://localhost:3000/books/123', { method: 'put', body: JSON.stringify({ uname: 'Zhang San', pwd: '789' }), headers: { 'Content-Type': 'application/json' } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); </script>
2.2 response format in fetchapi
- fetch is used to obtain data. If the response returns normally, the first thing we see is a response object, including a pile of returned original bytes. After receiving these bytes, we need to call methods to convert them into data in corresponding formats, such as JSON, BLOB or TEXT
/* Fetch Data format of response results */ fetch('http://localhost:3000/json').then(function(data){ // return data.json(); // Use JSON to transform the obtained data into an object return data.text(); // //Convert the obtained data into a string }).then(function(data){ // console.log(data.uname) // console.log(typeof data) var obj = JSON.parse(data); console.log(obj.uname,obj.age,obj.gender) })
http: request method:
1,OPTIONS
Return the HTTP request method supported by the server for specific resources. You can also test the functionality of the server by sending a '*' request to the web server
2,HEAD
Ask the server for a response consistent with the GET request, but the response body will not be returned. This method can obtain the meta information contained in the small response header without transmitting the whole response content.
3,GET
Make a request to a specific resource. Note: the get method should not be used in operations that produce "side effects". For example, in web applications, one reason is that get may be accessed arbitrarily by web spiders. Corresponding get request function in Loadrunner: web_link and web_url
4,POST
Submit data to specified resources for processing requests (such as submitting forms or uploading files). The data is contained in the request body. POST requests may lead to the establishment of new resources and / or the modification of existing resources. Corresponding POST request function in Loadrunner: web_submit_data,web_submit_form
5,PUT
Upload its latest content to the specified resource location
6,DELETE
The request server deletes the resource identified by the request URL
7,TRACE
Echo the request received by the server, which is mainly used for testing or diagnosis
8,CONNECT
HTTP/1.1 protocol is reserved for proxy servers that can change the connection to pipeline mode.
9,PATCH
PATCH method is newly introduced and is a supplement to PUT method. It is used to locally update known resources
reponse.text() and response The difference between json()
response.text() gets the of the text type
response.json() will help you run JSON once parse(response.text())
3.axios
Axios is a promise based HTTP library that can be used in browsers and node JS. Official website
- promise based for browsers and node JS http client
- Support browser and node js
- promise supported
- Can intercept requests and responses
- Automatically convert JSON data
- Ability to convert request and response data
3.1 basic usage of Axios
- get and delete requests pass parameters
- Through the traditional url? Pass parameters in the form of
- Pass parameters in restful form
- Pass parameters in params form
- post and put requests pass parameters
- Pass parameters through options
- Pass parameters through URLSearchParams
# 1. Send get request axios.get('http://localhost:3000/adata').then(function(ret){ # RET is an object. All objects exist in the data attribute of ret // Note that the data attribute is a fixed usage, which is used to obtain the actual data in the background // console.log(ret.data) console.log(ret) }) # 2. Get request pass parameters # 2.1 through the traditional url? Pass parameters in the form of axios.get('http://localhost:3000/axios?id=123').then(function(ret){ console.log(ret.data) }) # 2.2 transfer parameters in restful form axios.get('http://localhost:3000/axios/123').then(function(ret){ console.log(ret.data) }) # 2.3 transfer parameters in params form axios.get('http://localhost:3000/axios', { params: { id: 789 } }).then(function(ret){ console.log(ret.data) }) #3. The Axios delete request passes parameters in the same form as the get request axios.delete('http://localhost:3000/axios', { params: { id: 111 } }).then(function(ret){ console.log(ret.data) }) # 4. post request of Axios # 4.1 passing parameters through options axios.post('http://localhost:3000/axios', { uname: 'lisi', pwd: 123 }).then(function(ret){ console.log(ret.data) }) # 4.2 passing parameters through URLSearchParams var params = new URLSearchParams(); params.append('uname', 'zhangsan'); params.append('pwd', '111'); axios.post('http://localhost:3000/axios', params).then(function(ret){ console.log(ret.data) }) #5. The Axios put request is the same as the post request axios.put('http://localhost:3000/axios/123', { uname: 'lisi', pwd: 123 }).then(function(ret){ console.log(ret.data) })
3.2 axios global configuration
# Configure common request headers axios.defaults.baseURL = 'https://api.example.com'; # Configure timeout axios.defaults.timeout = 2500; # Configure common request headers axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; # Configure the content type of public post axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
3.3 axios interceptor
- request interceptor
- The function of the request interceptor is to perform some operations before the request is sent
- For example, a token is added to each request body, which is processed uniformly. It is also very easy to change it in the future
- The function of the request interceptor is to perform some operations before the request is sent
- Response interceptor
- The function of response interceptor is to perform some operations after receiving the response
- For example, when the server returns to the login status and fails and needs to log in again, jump to the login page
- The function of response interceptor is to perform some operations after receiving the response
# 1. Request interceptor axios.interceptors.request.use(function(config) { console.log(config.url) # 1.1 any request will go through this step. What should be done before sending the request config.headers.mytoken = 'nihao'; # 1.2 you must return here, otherwise the configuration will not succeed return config; }, function(err){ #1.3 what to do about request errors console.log(err) }) #2. Response interceptor axios.interceptors.response.use(function(res) { #2.1 what to do when receiving a response var data = res.data; return data; }, function(err){ #2.2 what to do about response errors console.log(err) })
4. async and await
- async is placed in front of the function as a keyword
- Any async function will implicitly return a promise
- The await keyword can only be used in functions defined using async
- await can be directly followed by a Promise instance object
- The await function cannot be used alone
- async/await makes asynchronous code look and behave more like synchronous code
# 1. Basic usage of Async # 1.1 async is put in front of the function as a keyword async function queryData() { # 1.2 the await keyword can only be used in functions defined using async. Await can be directly followed by a Promise instance object var ret = await new Promise(function(resolve, reject){ setTimeout(function(){ resolve('nihao') },1000); }) // console.log(ret.data) return ret; } # 1.3 any async function will implicitly return a promise. We can use then for chain programming queryData().then(function(data){ console.log(data) }) #2. Async function handles multiple asynchronous functions axios.defaults.baseURL = 'http://localhost:3000'; async function queryData() { # 2.1 after adding await, the following code will not be executed until the current await returns the result var info = await axios.get('async1'); #2.2 make asynchronous code look and behave more like synchronous code var ret = await axios.get('async2?info=' + info.data); return ret.data; } queryData().then(function(data){ console.log(data) })