1. JSON Server

Support cross-domain

1. Install the JSON server

npm install -g json-server
Copy the code

2. To createdb.jsonFile, copy the following

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
Copy the code

3. Start the JSON serverdb.jsonStart the terminal in the folder where the file is located

json-server --watch db.json
Copy the code

2. axios

2.1. What is Axios?

  1. The most popular ajax request library on the front end
  2. React/Vue officially recommends using Axios to make Ajax requests
  3. Axios quick table

2.2. Axios characteristics

  1. Asynchronous Ajax request library based on XHR + Promise
  2. It can be used on both the browser and Node sides
  3. Support for request/response interceptors
  4. Support request cancellation
  5. Request/response data transformation
  6. Send multiple requests in batches

2.3 Initiate a request directly using AXIos

Basic use of Axios

<! doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, User - scalable = no, initial - scale = 1.0, the maximum - scale = 1.0, Minimum-scale =1.0"> <meta http-equiv=" x-UA-compatible "content=" IE =edge"> <title> Axios </title> <link Crossorigin = "anonymous" href = "https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel = "stylesheet" > < script SRC = "https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js" > < / script > < / head > < body > < div Class ="container"> <h2 class="page-header"> </h2> <button class=" BTN btn-primary"> </button> <button Class =" BTN bTN-warning "> Send a POST request </button> <button class=" BTN bTN-success "> send a PUT request </button> <button class=" BTN BTN - danger "> send a DELETE request < / button > < / div > < script > / / access button const BTNS = document. QuerySelectorAll (" button"); // first BTNS [0]. Onclick = function () {// request type: 'GET', //URL: 'http://localhost:3000/posts? Id = 2 ', url: 'http://localhost:3000/posts/2', / / get a db. Json objects of id = 2}). Then (response = > {the console. The log (response); }); } // add a new article BTNS [1]. Onclick = function () {// send AJAX request axios({// request type method: 'POST', //URL URL: 'http://localhost:3000/posts', / / set the request body data: {/ / data from the data sent to the corresponding server title: "today the weather is good, also very beautiful", the author: }}). Then (response => {console.log(response); }); } // update data BTNS [2]. Onclick = function () {// send AJAX request axios({// request type: 'PUT', //URL URL: 'http://localhost:3000/posts/3', / / set the request body data: {/ / update the data from the data corresponding to the corresponding server path the title: "today the weather is good, also very beautiful", the author: }}). Then (response => {console.log(response); }); } // delete data BTNS [3]. Onclick = function () { 'http://localhost:3000/posts/3', / / delete the data in the corresponding path}). Then (response = > {the console. The log (response); }); } </script> </body> </html>Copy the code

Db. Json virtual server

{" posts ": [{" id" : 1, "title" : "json - server" and "author" : "typicode"}, {" id ": 2," title ":" college online is still silicon valley companies ", "author" : Small make up}], "comments" : [{" id ": 1," body ":" some comment ", "postId" : 1}, {" body ":" xi's rush ", "postId" : 2, "id" : 2 } ], "profile": { "name": "typicode" } }Copy the code

2.4 Axios common syntax

  • Axios (config): generic/essential way to send any type of request

  • Axios (url[, config]): You can specify only the URL to send a GET request

  • Axios.request (config): equivalent to axios(config)

  • Axios.get (url[, config]): sends a GET request

  • Axios.delete (url[, config]): sends a DELETE request

  • Axios. post(URL [, data, config]): sends a POST request

  • Axios. put(URL [, data, config]): sends a PUT request

  • Axios.defaults. XXX: The default global configuration of the request

  • Axios. Interceptors. Request. Use () : add request interceptor

  • Axios. Interceptors. Response. Use () : add response interceptors

  • Axios.create ([config]): Creates a new axios(it does not have the following functionality)

  • Axios.cancel (): Used to create an error object to Cancel the request

  • Axios.canceltoken (): The token object used to create the cancellation request

  • Axios.iscancel (): Whether it was an error to cancel the request

  • Axios.all (Promises): For batch execution of multiple asynchronous requests

  • Axios.spread (): Method used to specify the callback function that receives all success data

Axios path

/ * * below path is equal * axios ({* url: '/ post, * / / / post? a=100&b=200 * // /post/a/100/b/200 * // /post/a.100/b.200 * params: { * a:100, * b:200 * } * }) */Copy the code

2.5 Axios Syntax To initiate a request

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <div> <button onclick="testGet()"> </button> <button onclick="testPost()"> </button> <button onclick="testPost()"> </button> <button Onclick ="testPut()">PUT request </button> <button onclick="testDelete()"> </button> </div> <script SRC = "https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js" > < / script > < script > function testGet () { Axios. Get (' http://localhost:3000/posts') / / returns an array, Array has two objects / / axios. Get (' http://localhost:3000/posts/1 ') / / returns an object / / axios. Get (' http://localhost:3000/posts?id=1 ') / / Returns an array, Then (response => {console.log('/posts get', The response. The data)})} function testPost () {/ / add data axios. Post (' http://localhost:3000/posts' {" title ": "json-server3", "author": "typicode" }) .then(response => { console.log('/posts put', The response. The data)})} function testPut () {/ / update data axios. Put (' http://localhost:3000/posts/3 '{" title ": "json-server_put", "author": "typicode" }) .then(response => { console.log('/posts post', The response. The data)})} function testDelete () {/ / delete data axios. Delete (' http://localhost:3000/posts/3 '). Then (response = > { console.log('/posts delete', response.data) }) } </script> </body> </html>Copy the code

2.6 AXIOS global (default) configuration

< script > / / access button const BTNS. = the document querySelectorAll (" button "); // Axios.defaults. method = 'GET'; // Set the default request type to GET axios.defaults.baseURL = 'http://localhost:3000'; // Set the base URL axios.defaults.params = {id: 2}; // Set the default parameter axios.defaults.timeout = 3000; BTNS [0].onclick = function () {axios({url: '/posts'}).then(response => {console.log(response); }) } </script>Copy the code

3. Understanding and using difficult grammar

3.1 axios. Create (config)

  • A new AXIOS is created based on the specified configuration, that is, each new AXIOS has its own configuration

  • The new Axios just doesn’t have a way to cancel requests or batch them, and everything else is the same syntax

Why was this syntax designed?

  • Requirements: The configuration of some interfaces in the project is different from that of other interfaces. How to handle it (for example, multiple BaseurLs need to be specified)
  • Solution: Create two new Axios, each with its own unique configuration, to be applied to interface requests with different requirements
Const instance = axios.create({// instance is the function type baseURL: Instance ({url: '/posts'}) instance.get('/posts')Copy the code

Create an instance

<script> // Create instance object /getJoke const duanzi = axios.create({baseURL: 'https://api.apiopen.top', timeout: 2000}); const another = axios.create({ baseURL: 'https://b.com', timeout: 2000 }); // Duanzi ({// url: '/getJoke', //}).then(response => {// console.log(response); / /}); duanzi.get('/getJoke').then(response => { console.log(response.data) }) </script>Copy the code

3.2 Call order of interceptor function/Ajax request/request callback function

  • Note: Calling axios() does not send an Ajax request immediately, but rather requires a longer process
  • Flow: Request interceptor 2 => Request interceptor 1 => send ajax request => respond to interceptor 1 => respond to interceptor 2 => callback of the request
  • Note: This flow is strung together by promises, with the request interceptor passing config and the response interceptor passing Response
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title> interceptor </title> <script SRC = "https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js" > < / script > < / head > < body > < script > / / / / Promise Set the request interceptor config configuration object axios. Interceptors. Request. Use (function (config) {the console. The log (' request interceptor success - 1); Params = {a: 100}; // throw 'fail' return config; }, function (error) {console.log(' request interceptor failed - 1 '); return Promise.reject(error); }); Axios. Interceptors. Request. Use (function (config) {the console. The log (' request interceptor success - 2 '); // Modify the config parameter config.timeout = 2000; return config; }, function (error) {console.log(' request interceptor failed - 2 '); return Promise.reject(error); }); / / set the response interceptor axios. Interceptors. Response. Use (function (response) {the console. The log (' response interceptor success 1 '); Console. log(response); return response; }, function (error) {console.log(' response interceptor failed no. 1 ') return promise.reject (error); }); Axios. Interceptors. Response. Use (function (response) {the console. The log (' response interceptor success 2 ') / / can do some processing with the result of the response console.log(response.data); return response; }, function (error) {console.log(' response interceptor failed no. 2 ') return promise.reject (error); }); / / send the request axios ({method: "GET", url: "http://localhost:3000/posts"}), then (response = > {the console. The log (' custom callback to handle the result of the successful '); // console.log(response); }); </script> </body> </html>Copy the code

3.3 Canceling a Request

1. Basic process

  1. configurationcancelTokenobject
  2. The cache is used to cancel the requestcancelfunction
  3. Called later at a specific timecancelFunction cancel request
  4. Determine if in error callbackserror 是 cancelAnd do the corresponding processing
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title> Cancel request </title> <link crossorigin='anonymous' Href = "https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel = "stylesheet" > < script SRC = "https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js" > < / script > < / head > < body > < div class = "container" > < h2 Class ="page-header">axios </h2> <button class=" BTN btn-primary"> </button> <button class=" BTN btn-warning" > Request < / button > < / div > < script > / / access button const BTNS = document. QuerySelectorAll (" button "); //2. Declare global variable let cancel = null; BTNS [0].onclick = function(){if(cancel! == null){// Cancel the previous request; } axios({ method: 'GET', url: 'http://localhost:3000/posts', //1. CancelToken: new axios.CancelToken(function(c){//3. Assign c to cancel cancel = c; }) }).then(response => { console.log(response); Cancel = null; // Initialize the value of cancel. })} // Bind the second event to cancel the request BTNS [1]. } </script> </body> </html>Copy the code