Interface Call Method
-
Front and Back End Data Interaction Interface Calls
- Native AJAX
- AJAX based on jQuery
- Promise
- fetch API interface call
- axios interface call
- async/await interface call
-
URL Address Format
- Traditional URL s
- schema://host:port/path?query#fragment
- schema protocol. For example, http https ftp, etc.
- host domain name or IP address
- Port port, http default port 80, can be omitted
- Path path, for example/a B c/a/b/c
- Query query parameters, for example: uname=sunny&age=12
- fragment anchor (hash Hash), used to locate a location on the page
- Resful URL
- HTTP Request Method
- GET Query
- POST Add
- PUT Modification
- DELETE Delete
- HTTP Request Method
- schema://host:port/path?query#fragment
- Traditional URL s
Asynchronous programming
- asynchronous
- The JavaScript execution environment is "single threaded"
- Single-threaded means that only one thread in the JS engine is responsible for interpreting and executing JavaScript code, that is, only one task can be completed at a time.
- This task will not execute until the next one is completed. It will "block" other tasks. This task can be called the main thread
- Asynchronous mode can perform multiple tasks together
- Common asynchronous calls in JS
- Timed Tasks
- ajax
- Event Functions
- Dependency Analysis for Multiple Asynchronous Calls
- The result sequence of multiple asynchronous calls is uncertain
- Nesting is required for asynchronous call results if there is a dependency
// Callback to Hell $.ajax({ url: 'http://localhost:3000/data', success: function(data){ console.log(data); $.ajax({ url: 'http://localhost:3000/data1', success: function(data){ console.log(data); $.ajax({ url: 'http://localhost:3000/data2', success: function(data){ console.log(data); } }); } }); } });
Asynchronous Programming Promise Usage Details
-
Overview of Promise
- Promise is a solution for asynchronous programming
- Syntax, Promise is an object from which messages for asynchronous operations can be retrieved
-
Promise Benefits
- Avoid nesting of multi-tier asynchronous calls (callback to Hell)
- The Promise object provides an introductory API to make controlling asynchronous operations easier
Promise Basic Usage
-
Promise Basic Usage
- Instantiates a Promise object, a transfer function in a constructor that handles asynchronous tasks.
- The resolve and reject parameters are used to handle both success and failure scenarios, and the results are obtained through p.then
-
Promise Usage Steps
- Invocation of Promise
- We use new to construct a Promise, whose constructor receives a parameter that is a function
- And two parameters are passed in: resolve, reject, representing the callback function after the asynchronous operation succeeds and the callback function after the asynchronous operation fails, respectively.
- Implementing asynchronous tasks within functions
- Normally, resolve() outputs the result
- Exception, reject() output results
- After the Promise instance is generated, you can use the then method to specify the callback functions for the resolved and reject States
- In the then method, you can return the data directly instead of the Promise object, and then you can receive the data in the subsequent then
- Invocation of Promise
// Promise Basic Usage var p = new Promise(function(resolve, reject){ // This is used to implement asynchronous tasks setTimeout(function(){ var flag = true; if(flag) { resolve('hello'); }else{ reject('Error'); } }, 100); }); p.then(function(data){ console.log(data); },function(info){ console.log(info); })
Promise sends Ajax requests and handles callback hell
- Send Ajax requests based on Promise
- The return value of the last then() on then() is the call value of the next then()
- The then method specifies a callback function for the resolved and reject ed States
- The return value of then() can be either a Promise object or a non-Promise object
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 Handle normal conditions resolve(xhr.responseText); }else{ // 1.3 Handling Exceptions reject('Server Error'); } }; xhr.open('get', url); xhr.send(null); }); return p; } // Note: A service needs to be started here // In the then method, you can also directly return the data instead of the Promise object // You can receive data in the next queryData('http://localhost:3000/data0') .then(function(data){ console.log(data) // 1.4 Need to return to continue chain programming return queryData('http://localhost:3000/data1'); },function(info){ console.log(info); return queryData('http://localhost:3000/data1'); }) .then(function(data){ console.log(data); return queryData('http://localhost:3000/data2'); },function(info){ console.log(info); return queryData('http://localhost:3000/data2'); }) .then(function(data){ console.log(data); return 'End of data call!'; },function(info){ console.log(info); return 'End of data call!'; }) .then(function(data){ console.log(data); });
Return value of function in then method parameter
-
Return Promise instance object
- The returned instance object calls the next then
-
Return normal value
- The returned normal value is passed directly to the next then and is accepted by the parameter of the function in the then parameter
function queryData(url) { // 1.1 Create a Promise instance 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) { // 1.2 Handle normal conditions resolve(xhr.responseText); }else{ // 1.3 Handling Exceptions reject('Server Error'); } }; xhr.open('get', url); xhr.send(null); }); } // Note: A service needs to be started here // In the then method, you can also directly return the data instead of the Promise object // You can receive data in the next queryData('http://localhost:3000/data') .then(function(data){ return queryData('http://localhost:3000/data1'); }) .then(function(data){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve('Data call succeeded!); },1000) }) }) .then(function(data){ console.log(data); return 'End of data call!' }) .then(function(data){ console.log(data); });
Promise Common API s
- Instance Method
- p.then() gets the correct result for the asynchronous task
- p.catch() to get exception information
- p.finally() will be executed successfully or not (not yet a formal standard)
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') });
// Equivalent Writing function foo() { return new Promise(function(resolve, reject){ setTimeout(function(){ // resolve(123); reject('error'); }, 100); }) } foo() .then(function(data){ // Get the right results for asynchronous tasks console.log(data) },function(data){ // Get exception information console.log(data) }) // Success or failure will be enforced (not a formal standard) .finally(function(){ console.log('finished') });
-
Object Method
- Promise.all() processes multiple asynchronous tasks concurrently, and all tasks are executed to achieve results
- Promise.race() handles multiple asynchronous tasks concurrently, and results are obtained when only one task is completed
-
Promise.all()
- This 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, the item will be Promise.resolve to a promise
- Its status is determined by the three promise instances
-
Promise.race()
- This method also accepts an array as a parameter.
- When the state of one instance in p1, p2, and P3 changes (to fulfilled or rejected), the state of P changes.
- And pass the return value of the first promise to the callback function of p
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{ // Handle Exceptions reject('Server Error'); } }; xhr.open('get', url); xhr.send(null); }); } var p1 = queryData('http://localhost:3000/data'); var p2 = queryData('http://localhost:3000/data1'); var p3 = queryData('http://localhost:3000/data2'); // The parameters [p1,p2,p3] in all correspond to the results returned // ["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"] Promise.all([p1, p2, p3]).then(function(res){ console.log(res); }); //Because p1 executes faster, then() of Promise will get results // 'P1'. p2,p3 are still executing, but the execution results will be discarded. Promise.race([p1, p2, p3]).then(function(res){ console.log(res); });
FetchAPI overview and basic usage
-
Overview of Fetch
- Simpler data acquisition, more powerful and flexible, can be seen as an upgrade to xhr
- Peomise-based
- fetch is how ajax+Promise works
- And the $provided by jquery. ajax() almost
- fetch defaults to get request
-
Grammatical Structure
- The Fetch API is a new ajax solution Fetch will return Promise
- fetch is not a further encapsulation of ajax, but a native js, which does not use an XMLHttpRequest object
- fetch(url, options).then()
fetch(url).then(fn2) .then(fn3) .then(fn)
Interface call fetch usage
- Basic usage of fetch
- The first parameter is the path of the request, and Fetch returns Promise, so we can use the then to get the result of the successful request
- The text() method, which is part of the fetchAPI, returns a Promise instance object to get the data returned in the background
fetch('http://localhost:3000/fdata') .then(function(data){ return data.text(); }) .then(function(data){ console.log(data); })
fetch request parameters
-
Common Configuration Options
- method(String):HTTP request method, defaulted to GET(GET, POST, PUT, DELETE)
- Body (String): Request parameters for HTTP
- Headers (Object): Request header for HTTP, defaulting to {}
-
HTTP requests 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 requests
- You need to specify the corresponding method[method: requested method] in the options object
- When post ing and normal requests, request headers and bodies need to be set in options
-
Server-side configuration aspects
- If there is an application error
- Delete node_modules folder and package-lock.json file
- Reinstall npm install in the shell under this folder
- Arrays are recommended for request headers of the same level
- 'Access-Control-Allow-Headers', ['Content-Type', 'mytoken']
- If there is an application error
const express = require('express') const app = express() const bodyParser = require('body-parser') // Processing static resources app.use(express.static('public')) // Processing parameters to get data from POST app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Set up to allow cross-domain access to the service app.all('*', function (req, res, next) { res.header("Access-Control-Allow-Origin", '*'); res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('Access-Control-Allow-Headers', ['Content-Type', 'mytoken']); // Res.header ('Access-Control-Allow-Headers','mytoken'); // Error Root next(); }); // Routing Code // lsnrctl start app.listen(3000, () => { console.log('Network Server Operated...') })
- Parameter Passing by GET Request Mode
// Case comparison fetch('/abc?id=123') .then(data => { return data.text(); }).then(ret => { // Note: Here's the data you just got console.log(ret); }) fetch('/abc/123', { method: 'get' }).then(data => { return data.text(); }).then(ret => { // Note: Here's the data you just got console.log(ret); })
// GET parameter transfer - traditional url s pass through urls? Formal parameters fetch('http://localhost:3000/books?id=123', { method: 'get' // GET requests can be omitted from not writing the default is GET }) .then(function(data) { // 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) }); // Background Routing Interface app.get('/books', (req, res) => { res.send('Conventional URL Pass-through parameters!' + req.query.id) })
// GET parameter delivery - URL s in restful form pass parameters through/ // That is, id = 456 is related to the configuration of the ID background fetch('http://localhost:3000/books/456', { method: 'get' // GET requests can be omitted from not writing the default is GET }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); // Background Routing Interface app.get('/books/:id', (req, res) => { res.send('Restful Formal URL Pass-through parameters!' + req.params.id) })
- DELETE request mode parameter delivery
// DELETE Request Mode Parameter Pass // Delete ID is id=789 fetch('http://localhost:3000/books/789', { method: 'delete' }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); // Background Routing Interface app.delete('/books/:id', (req, res) => { res.send('DELETE Request Pass-through Parameters!' + req.params.id); })
- Parameter Passing by POST Request Mode
// POST Request Mode Parameter Passing fetch('http://localhost:3000/books', { method: 'post', body: 'uname=sunny&pwd=123', // Transfer data headers: { // Set Request Header 'Content-Type': 'application/x-www-form-urlencoded' // Specify submission method for form submission } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data); }); // Background Routing Interface app.post('/books', (req, res) => { res.send('POST Request Pass-through Parameters!' + req.body.uname + '---' + req.body.pwd); })
// POST Request Mode Parameter Passing fetch('http://localhost:3000/books', { method: 'post', body: JSON.stringify({ uname: 'sunny', pwd: '456' }), headers: { 'Content-Type': 'application/json' } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data); }); // Background Routing Interface app.post('/books', (req, res) => { res.send('POST Request Pass-through Parameters!' + req.body.uname + '---' + req.body.pwd); })
- Parameter Passing by PUT Request Mode
- Similar to POST, but also in two ways
// PUT Request Mode Parameter Passing 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) }); // Background Routing Interface app.put('/books/:id', (req, res) => { res.send('PUT Request Pass-through Parameters!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd) })
FetchAPI Response Data Format
-
Response format in fetch API
- fetch to get the data, and if the response returns normally, the first thing we see is a response object
- This includes the returned bunch of raw bytes
- These bytes need to be received and converted into data in the appropriate format by calling
- For example, JSON, BLOB or TEXT, etc.
-
Response data format
- text() treats the return body as a string type
- json() returns the result and JSON.parse(responseText) is the same
/* Fetch Data format text() for response results */ fetch('http://localhost:3000/json').then(function(data){ return data.text(); // //Convert the obtained data to a string }).then(function(data){ var obj = JSON.parse(data); console.log(data); console.log(data.uname,data.age); console.log(typeof data); // string console.log(obj.uname,obj.age,obj.gender); })
/* Fetch Data format json() for response results */ fetch('http://localhost:3000/json').then(function(data){ return data.json(); // Use json to transform the object for the data you get }).then(function(data){ console.log(data); console.log(data.uname); console.log(typeof data); // object })
axios overview and basic usage
- axios basic features
- promise-based for browsers and nodes. http client for JS
- Support for browsers and nodes. JS
- Support promise
- Ability to intercept requests and responses
- Automatically convert JSON data
- Ability to convert request and response data
axios basic usage
-
get and delete request pass parameters
- Through a traditional url? Formal transfer of parameters
- Pass parameter as restful
- Passing parameters as params
-
post and put request pass parameters
- Passing parameters through options
- Passing parameters through URLSearchParams
-
Send get request
- Import library file <script src='. / Js/axios. Js'></script>
- Get RET is an object, all objects exist in ret's data property
- Note: The data attribute is a fixed usage for getting the actual data in the background
// Send get request axios.get('http://localhost:3000/adata') .then(function(ret){ console.log(ret.data); console.log(ret); }) // Background interface code app.get('/adata', (req, res) => { res.send('Hello axios!'); })
Common API s for axios
-
Common API s
- get queries data
- post adds data
- put modifies data
- delete Delete data
-
get request pass parameter
- Through a traditional url? Formal transfer of parameters
- Pass parameter as restful
- Passing parameters as params
// Through a traditional url? Formal transfer of parameters axios.get('http://localhost:3000/axios?id=123') .then(function(ret){ console.log(ret.data); }) // Background code app.get('/axios', (req, res) => { res.send('axios get Pass-through parameters' + req.query.id) })
// Pass parameter as restful axios.get('http://localhost:3000/axios/123') .then(function(ret){ console.log(ret.data); }) // Background code app.get('/axios/:id', (req, res) => { res.send('axios get (Restful) Pass-through parameters' + req.params.id) })
// Passing parameters as params axios.get('http://localhost:3000/axios', { params: { id: 789 } }).then(function(ret){ console.log(ret.data) }) // Background code app.get('/axios', (req, res) => { res.send('axios get Pass-through parameters' + req.query.id) })
- delete request pass parameter
- The form of a parameter is the same as a get request
// Passing parameters as params axios.delete('http://localhost:3000/axios', { params: { id: 111 } }).then(function(ret){ console.log(ret.data) }) // Background code app.delete('/axios', (req, res) => { res.send('axios get Pass-through parameters' + req.query.id) })
- post request pass parameter
- Passing parameters through options
- Passing parameters through URLSearchParams
// Passing parameters through options axios.post('http://localhost:3000/axios', { uname: 'sunny', pwd: 123 }).then(function(ret){ console.log(ret.data); }) // Background code app.post('/axios', (req, res) => { res.send('axios post Pass-through parameters' + req.body.uname + '---' + req.body.pwd); })
// Passing parameters through options var params = new URLSearchParams(); params.append('uname', 'Tom'); params.append('pwd', '025'); axios.post('http://localhost:3000/axios', params).then(function(ret){ console.log(ret.data); }) // Background code app.post('/axios', (req, res) => { res.send('axios post Pass-through parameters' + req.body.uname + '---' + req.body.pwd); })
- put request pass parameter
- Same as post request
// Passing parameters through options axios.put('http://localhost:3000/axios/123', { uname: 'Jerry', pwd: 123567 }).then(function(ret){ console.log(ret.data); }) // Background code app.put('/axios/:id', (req, res) => { res.send('axios put Pass-through parameters' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd) })
Response results from axios
- Main properties of response results
- The data actually responded back
- headers Response Header Information
- status Response status Code
- statusText Response Status Information
// Response string data axios.get('http://localhost:3000/axios?id=987') .then(function(ret){ console.log(typeof ret.data); console.log(ret.data); console.log(ret); }) // Backend Code app.get('/axios', (req, res) => { res.send('axios get Pass-through parameters' + req.query.id) })
// Response Object Data axios.get('http://localhost:3000/axios-json') .then(function(ret){ console.log(typeof ret.data); console.log(ret.data); console.log(ret); }) // Backend Code app.get('/axios-json', (req, res) => { res.json({ uname: 'Jerry', age: 12 }); })
Global configuration of axios
-
Configure default address
- axios.defaults.baseURL = 'https://api.example.com';
-
Configure timeout
- axios.defaults.timeout = 2500;
-
Configure Public Request Header
- axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
- Background cross-domain configuration
- res.header('Access-Control-Allow-Headers', ['Content-Type', 'mytoken']);
- Background cross-domain configuration contains the same key values in an array, and writing them individually is likely to cause errors
-
Configure Common post Content-Type
- axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
/* axios Response results and global configuration */ // Configure timeout axios.defaults.timeout = 10; // Configure Base URL Address for Request axios.defaults.baseURL = 'http://localhost:3000'; // Configure Request Header Information axios.defaults.headers.common['mytoken'] = 'hello'; axios.get('axios-json') .then(function(ret){ console.log(ret.data); })
axios interceptor
- request interceptor
- The purpose of request interceptors is to do something before a request is sent
- For example, adding token to each request body makes it easy to unify the processing and change it later
axios.interceptors.request.use(function(config) { console.log(config.url) // Any request will go through this step and do something before sending the request config.headers.mytoken = 'nihao'; // Make sure to return here otherwise the configuration is unsuccessful return config; }, function(err){ // What to do about request errors console.log(err) }) axios.get('http://localhost:3000/adata') .then(function(data){ console.log(data); })
- Response Interceptor
- The purpose of response interceptors is to do something after receiving a response
- For example, if the server fails to return to the login state and needs to log in again, jump to the login page
axios.interceptors.response.use(function(res) { // What to do in receiving a response var data = res.data; return data; }, function(err){ // What to do about response errors console.log(err) }) axios.get('http://localhost:3000/adata') .then(function(data){ console.log(data); })
axios.interceptors.request.use(function(config) { console.log(config.url); // Any request will go through this step and do something before sending the request config.headers.mytoken = 'success'; // Make sure to return here otherwise the configuration is unsuccessful return config; }, function(err){ // What to do about request errors console.log(err) }) axios.interceptors.response.use(function(res) { // What to do in receiving a response var data = res.data; console.log(data+ 'Response Interception'); return data; }, function(err){ // What to do about response errors console.log(err) }) axios.get('http://localhost:3000/adata') .then(function(data){ console.log(data); })
Overview and basic usage of async/await asynchronous functions
- Overview of async/await
- async/await is a new syntax introduced by ES7 to facilitate asynchronous operations
- The async keyword is used on a function (the return value of the async function is a Promise instance object)
- The await keyword is used in the async function (await can get asynchronous results)
async function queryDate(id){ const ret = await axios.get('/data'); return ret; } queryData.then(ret=>{ console.log(ret); })
Basic usage of async/await
-
Place async in front of the function as a keyword
- Any async function implicitly returns a promise
-
The await keyword can only be used in functions defined with async
- Wait can be followed directly by a Promise instance object
- The await function cannot be used alone
-
async/await makes asynchronous code look and behave more like synchronous code
- The await function cannot be used alone, and the async function returns a Promise object
- You can use the then function to add callback functions
- When a function executes, it returns a Promise object once it encounters the await function
- Wait until the asynchronous operation is complete before executing the following statement
axios.defaults.baseURL = 'http://localhost:3000'; /* async function queryData(){ const ret = await axios.get('adata'); return ret.data; } */ async function queryData(){ var ret = await new Promise(function(resolve, reject){ setTimeout(function(){ resolve('Hello'); },2000) }); return ret; } queryData().then(function(data){ console.log(data); })
async/await handles multiple asynchronous requests
- Function handles multiple asynchronous functions
- After adding await, the current await returns the result before executing the following code
- Make asynchronous code look more like synchronous code
// Multiple Asynchronous Calls 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); }) // Background routing code app.get('/async1', (req, res) => { res.send('hello') }) app.get('/async2', (req, res) => { if(req.query.info == 'hello') { res.send('world') }else{ res.send('error') } })
Case: Book Management System
-
Book-related operations operate on background interface data
-
Function point that requires calling interface
- Book List Data Loading GET http://localhost:3000/books
- Add Book POST http://localhost:3000/books
- Verify the existence of GET for book names http://localhost:3000/books/book/:name
- Edit Books - Query book information GET based on ID http://localhost:3000/books/:id
- Edit Book - Submit Book Information PUT http://localhost:3000/books/:id
- Delete Book DELETE http://localhost:3000/books/:id