[Axios] Send request / API / understanding and use

Table of contents

1. HTTP related (preparation work)

1.1 The basic process of HTTP request interaction

1.2 Request message

1.3 Response message

1.4 Common response status codes

1.5 Request method and request parameters

1.6 Detailed explanation of HTTP and its versions (HTTP1.0, HTTP1.1, HTTP2.0, HTTP3.0)

http1.0

http1.1

http2.0

http3.0/QUIC

2.1 Classification of APIs

2.2 Use json-server to build a REST API

2.2.1 What is json-server?

2.2.2 Using json-server

2.2.3 Access the test using a browser

2.2.4 Use postman to test the interface

2.2.5 General http request and ajax request

3 Understanding and using axios

3.1 What is axios?

3.2 Features of axios

3.2 Basic usage of axios

3.3 Axios common configuration items

3.4 axios.create method

3.5 Interceptors in axios

3.6 cancel request in axios

3.7 Axios sends requests in batches


1. HTTP related (preparation work)

1.1 The basic process of HTTP request interaction

  1. The foreground application sends an HTTP request (request message) from the browser to the server
  2. After the background server receives the request, it dispatches the server application to process the request, and returns an HTTP response (response message) to the browser
  3. The browser receives the response, parses and displays the response body/calls the monitoring callback

1.2 Request message

HTTP request message consists of request line, request header, blank line and request body (body).

  1. Request line
    methodurl:GET/product_detail?id=2POST/login
  2. Multiple request headers
    Host: www.baidu.com
    Cookie: BAIDUID=AD3B0FA706E; BIDUPSID=AD3B0FA706;
    Content-Type: application/x-www-form-urlencoded
    or application/json
  3. Request body
    username=tom&pwd=123
    {"username":"tom","pwd":123}

1.3 Response message

HTTP response message consists of status line, response header, blank line and response body (body)

  1. Response status line: statusText
  2. Multiple response headers
    Content-Type:text/html;charset=utf-8
    Set-Cookie:BD_CK_SAM=1;path=/
  3. Response body html text/json text/js/css/picture...

1.4 Common response status codes

100, the accepted request is being processed, the information status code
200 is OK, the request is successful. Generally used for GET and POST requests
201 Created has been created. Successfully requested and created a new resource

301, permanent redirection , indicating that the resource has been assigned a new URL

For example, when we visit  http://www.baidu.com ,  we will jump to  https://www.baidu.com . After sending the request, it will return a 301 status code, and then return a location, prompting the new address. The browser It will take this new address to visit.

302, temporary redirection , indicating that the resource is temporarily assigned a new URL
. For example, a user who is not logged in visits the user center and is redirected to the login page

303, indicating that there is another URL for the resource, use the GET method to obtain the resource
304, (unmodified) The requested web page has not been modified since the last request. When the server returns this response, it will not return the webpage content
401 Unauthorized/The request requires the user's identity authentication
404 NotFound The server cannot find the resource according to the client's request
500 InternalServerError The server has an internal error and cannot complete the request

1.5 Request method and request parameters

1. Request method

  1. GET: Read data from the server to check (get request cannot send request body parameters)
  2. POST: add
  3. PUT: Update server-side data Change
  4. 4DELETE: Delete server-side data delete

2. Request parameters

1. query parameter (query string parameter)

  1. The parameters are contained in the request address, the format is:/xxxx?name=tom&age=18
  2. Do not use query parameters for sensitive data, because the parameters are part of the address, which is more dangerous
  3. Remarks: The query parameter is also called the query string parameter , and the encoding method isurlencoded

2. params parameter

  1. The parameters are contained in the request address, the format is:
    http://localhost:3000/add_person/tom/18
  2. Do not use the params parameter for sensitive data, because the parameter is part of the address, which is more dangerous

3. Request body parameters

  1. Parameters are contained in the request body and can be viewed through browser development tools
  2. There are two commonly used formats:
    Format 1: urlencodedFormat
    For example:  name=tom&age=18
    corresponding request header: Content-Type:application/x-www-form-urlencoded
    Format 2: json format
    For example, {“name”:“Tom”,“age”:18}
    corresponding request header:Content-Type:application/json

pay attention

  1. GET requests cannot carry request body parameters, because GET requests do not have request bodies
  2. In theory, a request can use any of the above three types of parameters at will, and even a request of three parameters can be carried in three forms, but generally do not do so.
  3. Generally speaking, there are some customary rules:
    (1) For example, when a form form sends a POST request: automatically use the request body parameters and use urlencoded encoding.
    (2) For example, when jQuery sends an ajax-post request: automatically use the request body parameters and use urlencoded encoding.
  4. Who is the development request sent to? What request? What parameters to carry? . . . API interface documentation of the reference project

1.6 Detailed explanation of HTTP and its versions (HTTP1.0, HTTP1.1, HTTP2.0, HTTP3.0)

http1.0

  • The default short connection
    is a TCP connection for a resume request, and it will be disconnected after the request is completed. (for each request 三次握手)
  • Support HEAD, POST method, add status code
  • Transmission content is not limited to HTML files
  • 不允许断点续传,
    you can't just transfer a part, you need to transfer the whole object

http1.1

  • For cache processing ,
    in HTTP1.0 If-Modified-Since, Expires in the header is mainly used as the standard for cache judgment. HTTP1.1 introduces more cache control strategies such as Entity tag, If-None-Match, If-Unmodified-Since, If-Match, Last-Modifyand more optional cache headers to control caching strategy.

  • Bandwidth optimization and the use of network connections
    In HTTP1.0, there are some phenomena of wasting bandwidth. For example, the client only needs a part of an object, but the server sends the entire object, and does not support the function of resuming uploads . HTTP1 .1 introduces the range header field in the request header, which allows only a certain part of the resource to be requested, that is, the return code is 206 (Partial Content), which is convenient for developers to choose freely to make full use of bandwidth and connections.

  • Management of error notification:
    24 new error status response codes have been added in HTTP1.1, such as 409 (conflict) indicating that the requested resource conflicts with the current state of the resource; 410 (Gone) indicating that a resource on the server is permanently delete.

  • Host header processing:
    In HTTP1.0, each server is considered to be bound to a unique IP address, so the URL in the request message does not pass the host name . But with the development of virtual host technology, multiple virtual hosts can exist on one physical server, and they share one IP address. Both HTTP1.1 request messages and response messages should support the Host header field, and if there is no Host header field in the request message, an error (400 Bad Request) will be reported.

  • 长连接(Connection: keep-alive):
    HTTP1.1 supports long connection and request pipeline processing. Multiple HTTP requests and responses can be transmitted on one TCP connection, which reduces the consumption and delay of establishing and closing connections. It is enabled by default in HTTP1.1, which makes up for it to a certain extent Connection:keep-alive. HTTP1.0 has the disadvantage of creating a connection for each request. (serial)

http2.0

  • multiplexing

    HTTP2.0 uses multiplexing technology to achieve concurrent processing of the same connection 多个请求, and the number of concurrent requests is several orders of magnitude higher than HTTP1.1. HTTP1.1 can also establish several more TCP connections to handle more concurrent requests, but creating a TCP connection itself also has overhead. (parallel)

  • header data compression

    In HTTP1.1, HTTP request and response are composed of three parts: status line, request/response header, and message body. Generally speaking, the message body is compressed by gzip, or the compressed binary file itself is transmitted, but the status line and header are not compressed, and are directly transmitted in plain text. As Web functions become more and more complex, the number of requests generated by each page is also increasing, resulting in more and more traffic consumed in the header , especially when UserAgent and Cookie are transmitted every time, which do not change frequently The content is a complete waste.

    HTTP1.1 does not support the compression of header data. HTTP2.0 uses  the HPACK algorithm to compress header data, so that the data volume is small and the transmission on the network will be faster.
    (http 2.0 uses the encoder to reduce the size of the headers to be transmitted, and each communication party caches a header field table, which avoids the repeated transmission of headers and reduces the size of the transmission)

  • server push

    Server push is a mechanism for sending data ahead of a client request. A web page uses many resources: HTML, style sheets, scripts, images, and so on. Each of these resources must be explicitly requested in HTTP 1.1. It's a slow process. The browser starts by fetching HTML, and incrementally fetches more resources as it parses and evaluates the page. Because the server has to wait for the browser to make every request, the network is often idle and underutilized.

    In order to improve the delay, HTTP2.0 introduces  server push , which allows the server to push resources to the browser, before the browser makes a clear request, so that the client will not create a connection again to send a request to the server for acquisition. In this way, the client can directly load these resources locally without going through the network.

  • stream priority

    The priority value can be set for the data flow, which determines the different priority strategies adopted by the client and the server to process different flows. (For example, while the browser is waiting for critical CSS or JS files to finish rendering the page, the server is focusing on loading images)

  • Use binary framing layer

    Add a binary framing layer between the application layer and the transport layer, and divide all transmitted information into smaller messages and frames without changing the semantics of HTTP (HTTP method, status code, URI and header fields) , and encode them in binary format to improve transmission performance and achieve low latency and high throughput.

    The header information of HTTP1.x will be encapsulated into the Headers frame, and our request body will be encapsulated into the Data frame.

http3.0/QUIC

  • Reduced TCP三次握手TLS handshake time based on UDP:

    HTTP1.0/1.1/2.0/HTTPS are used TCPfor transmission, HTTP2/HTTPS also need to use TLSthe protocol for secure transmission. There are two handshake delays, and QUIC based on the connectionless UDP protocol requires only one interaction when the connection is established, which is equivalent to half the handshake time.

  • Solve the problem of head-of-line blocking when multiplexing packets are lost:

    There are no dependencies between multiple streams on a connection in QUIC. Therefore, when packet loss occurs, it will only affect the current stream, thereby avoiding the head-of-line blocking problem.

  • Optimize retransmission strategy:

    Due to a problem in TCP, 重传序号一致the sender cannot determine whether the ACK is an acknowledgment of the initial packet or an acknowledgment of the retransmitted packet. In order to avoid this problem, the QUIC sender sets each initial and retransmitted packet to use a unique packet number, each number is unique and strictly incremented, so that each time an ACK is received, it can be based on The number clearly determines whether the ACK is from the original packet or a retransmission packet.

  • flow control:

    In order to avoid streams with extremely slow traffic, QUIC uses flow control at the connection layer (connection flow control) and Stream layer (stream flow control) to limit the maximum buffer size that a single Stream can occupy.

  • Connection migration:

    The QUIC connection does not use a quadruple as an identifier (source IP, source port, destination IP, destination port) (the TCP connection needs to be switched when the connection changes), but uses a 64-bit random number Connection ID, corresponding to each stream, Even if the IP or port changes, as long as the Connection ID does not change, the connection can still be maintained.

2.1 Classification of APIs

  1. REST API: restful (Representational State Transfer (resource) presentation layer state conversion)
    (1) Send a request for CRUD, which operation is determined by the request method
    (2) The same request path can perform multiple operations
    (3) The request method will be used GET/POST/PUT/DELETE
  2. Non-REST API: restless
    (1) The request method does not determine the requested CRUD operation
    (2) A request path only corresponds to one operation
    (3) Generally only GET/POST

2.2 Use json-server to build a REST API

2.2.1 What is json-server?

A toolkit for quickly building a REST API
Quickly build a server in 10 seconds

2.2.2 Using json-server

在线文档: GitHub - typicode/json-server: Get a full fake REST API with zero coding in less than 30 seconds (seriously)

  1. Download and install (global): npm install -g json-server
  2. Create a database json file in the target root directory: db.json
  3. Start the server and execute the command: json-server --watch db.json

// db.json 文件
{
	"posts": [
		{ "id": 1, "title": "json-server", "author": "typicode" },
		{ "id": 2, "title": "json-server2", "author": "typicode" }
	],
	"comments": [
		{ "id": 1, "body": "some comment", "postId": 1 }
	],
	"profile": { "name": "typicode" }
}

2.2.3 Access the test using a browser

http://localhost:3000/posts
http://localhost:3000/posts/1

2.2.4 Use postman to test the interface

Test GET/POST/PUT/DELETE

The server simulated by json-server, the id must be carried  with params  , and the other can use the request body:
http://localhost:3000/students/3

GET query parameters


get Params parameter

request body urlencoded form

request body json form

2.2.5 General http request and ajax request

  1. ajax(xhr) request is a special kind of  httprequest
  2. On the server side, there is no difference, the difference is on the browser side
  3. Browser-side request: only XHRor fetchsent is ajaxthe request , all other are non-ajax requests
  4. The browser receives the response
    (1) General request: the browser will generally display the response body data directly, which is what we often call refreshing/jumping the page
    (2) Ajax request: the browser will not perform any update operations on the interface, Just call the callback function of the monitoring and pass in the relevant data of the response

3 Understanding and using axios

3.1 What is axios?

  1. The most popular ajax request library on the front end
  2. react/vue officially recommends using axios to send ajax requests
  3. 文档: GitHub - axios/axios: Promise based HTTP client for the browser and node.js

3.2 Features of axios

  1. Promise-based asynchronous ajax request library
  2. Both the browser end and the node end can be used
  3. Support for request/response interceptors
  4. Support Request Cancellation
  5. Request/Response Data Conversion
  6. Batch multiple requests

The interface document is: Write some comments by the tool api-doc, and it can be generated. Get
the document and test it with postman first

3.2 Basic usage of axios

introduce

  1. The return value of an axios call is a Promise instance.
  2. The successful value is called response, and the failed one is called error.
  3. The successful value of axios is a response object encapsulated by axios, and the real data returned by the server is in response.data
  4. Configuration items with query parameters are called params
  5. When carrying params, you need to manually splice them in the url

axios(config): the general/most essential way to send any type of request
axios(url[, config]): can only specify the url to send a get request
axios.request(config): is equivalent to axios(config)
axios.get(url[, config]): sending a get request
axios.delete(url[, config]): and sending a delete request
axios.post(url[, data, config]): sending a post request
axios.put(url[, data, config]): and sending a put request

axios.defaults.xxx: Default global configuration for requests (method\baseURL\params\timeout...)
axios.interceptors.request.use(): Add request interceptor
axios.interceptors.response.use(): Add response interceptor

axios.create([config]): Create a new axios (it doesn't have the functions below)

axios.Cancel(): The error object used to create the cancellation request
axios.CancelToken(): is used to create the token object of the cancellation request.
axios.isCancel(): Whether it is a cancellation request error
axios.all(promises): Used to execute multiple asynchronous requests in batches.
Axios.spread(): Used to specify to receive all successes The method of data callback function
————————————————

<script type = "text/javascript" src="./js/axios.min.js"></script>
<button id="btn1"> 点我获取所有人</button>
<button id="btn1"> 点我获取某个人</button>
<input id="person_id" type="test" placeholder="请输入一个人的id"> </input>
<button id="btn3"> 点我添加一个人</button>
<input id="person_name" type="test" placeholder="请输入名字"> </input>
<input id="person_age" type="test" placeholder="请输入年龄"> </input>
<button id="btn4"> 点我更新一个人</button>
<input id="person_update_id" type="test" placeholder="请输入id"> </input>
<input id="person_update_name" type="test" placeholder="请输入名字"> </input>
<input id="person_update_age" type="test" placeholder="请输入年龄"> </input>
<button id="btn5"> 点我删除一个人</button>
<input id="person_delete_id" type="test" placeholder="请输入闪删除的的id"> </input>

const btn1 = document.getELementById('btn1')
const btn2 = document.getELementById('btn2')
const btn3 = document.getELementById('btn3')
const btn4 = document.getELementById('btn4')
const btn4 = document.getELementById('btn4')
const btn5 = document.getELementById('btn5')
const personId = document.getElementByid('person_id')
const personName = document.getElementByid('person_name')
const personAge = document.getElementByid('person_age')
const personUpdateId = document.getElementByid('person_update_id')
const personUpdateName = document.getElementByid('person_update_name')
const personUpdateAge = document.getElementByid('person_update_age')
const personDeleteId = document.getElementByid('person_delete_id')
// 获取所有人信息-发送 GET 请求-不携带参数
btn1.onclick=()=>{

    // 完整版
    axios({
		url:'http://localhost:5000/test1?delay=5000',//请求地址,延迟5秒
		method:'GET',
		timeout:2000, //配置超时时间
	}).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{console.log('请求失败了!',error);}
	)

	// 精简版
	axios.get('http://localhost:5000/person').then(
		response=>{ console.log('请求成功了!',response.data); },
		error=>{console.log('请求失败了!',error);}
	)
}
//获取某个人的信息-发送GET请求-携带query参数
btn2.onclick=()=>{

    // 完整版
    axios({
		url:'http://localhost:5000/person',
		method:'GET',
		params:{id:personId.value} 
		// 此处写的是params,但是携带的是query参数 
	}).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{console.log('请求失败了!',error);}
	)

	// 精简版
	axios.get('http://localhost:5000/person', {params:{id:personId.value}}).then(
		response=>{ console.log('请求成功了!',response.data); },
		error=>{console.log('请求失败了!',error);}
	)
}
// 添加一个人,年龄和名字--发送POST请求--携带json编码参数或urlencoded编码
btn3.onclick=()=>{

    // 完整版
    axios({
		url:'http://localhost:5000/person',
		method:'POST',
		// 1. 携带请求体参数,json编码
		data:{name:personName.value,age:personAge} 
		
		// 2. 携带请求体参数,urlencoded编码
		data:`name=${personName.value}&age=${personAge.value}`	
	}).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{console.log('请求失败了!',error);}
	)

	// 精简版
		// 1. 携带请求体参数,json编码
		axios.post('http://localhost:5000/person',
		{name:personName.value,age:personAge} ).then( 
            response=>{ console.log('请求成功了!',response.data); },
		    error=>{console.log('请求失败了!',error);}
	)

	    // 2. 携带请求体参数,urlencoded编码
	 	axios.post('http://localhost:5000/person',
	 		`name=${personName.value}&age=${personAge.value}`).then( 
		response=>{ console.log('请求成功了!',response.data); },
		error=>{console.log('请求失败了!',error);}
	)
}
// 更新某个人--发送PUT请求--携带json编码参数或urlencoded编码
btn4.onclick=()=>{

    // 完整版
    axios({
		url:'http://localhost:5000/person',
		method:'PUT',
		data:{id:personUpdateId.value,
			name:personUpdateName.value,
			age:personUpdateAge.value,
		} 	
	}).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{console.log('请求失败了!',error);}
	)

	// 精简版
	axios.put('http://localhost:5000/person',{id:personUpdateId.value,
			name:personUpdateName.value,
			age:personUpdateAge.value}).then( 
		response=>{ console.log('请求成功了!',response.data); },
		error=>{console.log('请求失败了!',error);}
	)
}
// 删除某个人--发送DELETE请求--携带parmas
btn5.onclick=()=>{
    // 完整版
    axios({
		url:`http://localhost:5000/person/${personDeleteId.value}`,
		method:'DELETE',	
	}).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{console.log('请求失败了!',error);}
	)
}

3.3 Axios common configuration items

axios.defaults.xxxRequested default global configuration

<script type = "text/javascript" src="./js/axios.min.js"></script>
// 给 axios配置默认配置
axios.defaults.timeout = 2000
axios.defaults.headers = {name:atjm}
axios.defualts.baseURL = 'http://localhost:5000'

<button id="btn"> 点我获取所有人</button>
const btn1 = document.getELementById('btn')
btn.onclick=()=>{
    // 完整版
    axios({
		url:'http://localhost:5000/person',//请求地址,
		method:'GET', //请求方式
		//params:{a:1,b:2},//配置query
		//data:{a:3,d:3}, //配置请求体 参数 (json)
		//data:'e=5&f=6' //配置请求体参数(urlencoded)
		timeout:2000, //配置超时时间
		header:{demo:123} //配置请求头
		responseType:'json' //配置相应数据格式(默认值)
	}).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{console.log('请求失败了!',error);}
	)
}

3.4  axios.createMethod

axios.create([config]): Create a new axios (it does not have the following functions)

axios.create(config)

  1. Create a new according to the specified configuration axios, that is, each new axioshas its own configuration
  2. The new one axiosis that there is no method for canceling requests and sending requests in batches, and all other syntaxes are consistent
  3. Why is this grammar designed?
    (1) Requirement: Some interfaces in the project require different configurations than other interfaces.
    (2) Solution: Create 2 new axios, each with its own unique configuration, Applied to interface requests with different requirements
const axios2 = axios.create({
	timeout: 2000
	//headers: {name:atjm}
	baseURL:'http://localhost:5000'
})
// 需要放在defaluts前方
btn.onclick =()=>{
    // 完整版
    axios2({
		url:'http://localhost:5000/person',//请求地址,
		method:'GET', //请求方式
		//params:{a:1,b:2},//配置query
		//data:{a:3,d:3}, //配置请求体 参数 (json)
		//data:'e=5&f=6' //配置请求体参数(urlencoded)
		timeout:2000, //配置超时时间
		header:{demo:123} //配置请求头
		responseType:'json' //配置相应数据格式(默认值)
	}).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{console.log('请求失败了!',error);}
	)
}

axiosInterceptors in 3.5 

axios request interceptor

  1. what is it
    A callback function executed before actually sending the request
  2. Role: Unified processing of all requests: add request headers, add parameters, interface loading prompts, etc.

axiosresponse interceptor

  1. what is it
    A set of callback functions executed after getting the response
  2. Function: If the request is successful, process the successful data;
               if the request fails, perform unified operations on the failure

The calling order of the interceptor function/  ajax request/request's callback function.
Explanation: The call  axios()does not send the request immediately ajax , but needs to go through a long process
Process: Request Interceptor 2 => Request Interceptor 1 => Send ajax Request => Response Interceptor 1 => Response Interceptor 2 => Requested Callback
Note: This process is  promise connected in series, the request interceptor passes config, and the response interceptor passesresponse

// 请求拦截器
axios.interceptors.request.use((config)=>{
	 if(Date.now()%2 === 0){
	 	config.headers.token ='atuge'
	 }
	 return config;
})

// 响应拦截器
axios.interceptors.response.use(
	response=>{
		console.log('响应拦截器成功的回调执行了',response)
		if(Date.now()%2 === 0)	return response.data
		else		return '时间戳不是偶数,不能给你数据'
	},
	error=>{
		console.log('响应拦截器失败的回调执行了')
		alert(error)
		return new Promise(()=>{})
	}
)
btn.onclick=() async() =>{
    const result = await axios.get('http://localhost:5000/person')
    console.log(result);
}

axiosCancellation request in 3.6 

  1. Basic process
    Configure cancelTokenobject
    Cache the cancel function for canceling the request
    Call the cancel function at a specific time to cancel the request
    In the error callback, judge if the error is cancel and deal with it accordingly
  2. Realize the function
    Click the button to cancel a request that is being requested
    Before requesting an interface, cancel the previous unfinished request

cancel request 1

let cancel;

btn1.onclick = async() =>{
    // 完整版
    axios({
		url:'http://localhost:5000/person',
		cancelToken:new CancelToken((c)=>{
			console.log(c) //c是一个函数,调用c可以关闭本次请求
			cancel = c
		})
	}).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{console.log('请求失败了!',error);}
	)
}

btn2.onclick=()=>{
	cancel('任性,就是不要了')
}

cancel request 2

// CancelToken 能为一次请求“打标注"
const {CancelToken, isCancel} = axios
let cancel;

btn1.onclick=() async() =>{
    if(cancel) cancel()
    axios({
		url:'http://localhost:5000/test?delay=3000',
		cancelToken:new CancelToken((c)=>{
			console.log(c) //c是一个函数,调用c可以关闭本次请求
			cancel = c
		})
	}).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{
			if(isCancel(error))
				console.log('用户取消了请求,原因是',error,message)
			else
				console.log('请求失败了!',error);}
	)
}

btn2.onclick=()=>{
	cancel('任性,就是不要了')
}

Cancel request 3 cancel request + interceptor

// CancelToken 能为一次请求“打标注"
// isCancel 判断错误是真的错误还是用户取消请求导致的
const {CancelToken,isCancel}= axios
let cancel;

// 请求拦截器
axios.interceptors.request.use((config)=>{
	if(cancel) cancel('取消了')
	config.CancelToken = new CancelToke((c)=> cancel=c)
	return config;
})

// 响应拦截器
axios.interceptors.response.use(
	response=>{ return response.data },
	error=>{
        // 如果进入判断,证明是用户取消了请求
		if(isCancel(error)) 
			console.log('用户取消了请求,原因是',error.message)
		else
			console.log('失败了',error)
		return new Promise(()=>{})
	}
)

btn1.onclick = async() =>{
    const result = await axios.get('http://localhost:5000/test?delay=3000')
	
}
btn2.onclick=()=>{
	cancel('任性,就是不要了')
}

3.7  axiosSending requests in batches

btn1.onclick = async() =>{
   axios.all([
   	  axios.get('http://localhost:5000/test'),
   	  axios.get('http://localhost:5000/test2?delay=3000'),
   	  axios.get('http://localhost:5000/test3')
   ]).then(
		response=>{ console.log('请求成功了!',response.data);},
		error=>{console.log('请求失败了!',error);}
	)
}

Guess you like

Origin blog.csdn.net/qq_37308779/article/details/126357165