Based on the Promise interface calling method ajax fetch axios async / await front-end interaction

  1. Promise usage
  2. Interface call fetch usage
  3. Interface call axios usage
  4. Interface call async / await usage

A Promise usage

Promise
resolve success status
rejectrejection status
thenis the processing of returning the promise before

Promise related concepts The
new es6 syntax is used to handle asynchronous programming. A
promise is an object that can obtain the message benefits of asynchronous operations
:

  1. Can avoid the problem of multiple layers of asynchronous call nesting (callback hell)
  2. Provides a concise API to make it easier to control asynchronous operations

Send ajax request based on promise

// 封装一个独立的函数
function queryData(){
	return pro = new Promise((resolve, reject)=>{
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = () =>{
			if(xhr.readyState != 4) return;
			if(xhr.readyState == 4 && xhr.status == 200){
				// 处理正常的情况
				resolve(xhr.responsetext)
			}else{
				// 处理异常情况
				reject('服务器错误')
			}
		}
		xhr.open('get', url); // 准备发送前的参数
		xhr.send(null);
	});
}
// 单个ajax请求
queryData('http://localhost:3000/data')
	.then((data)=>{
		console.log(data)
	},(info)=>{
		console.log(info)
	})
// 多个ajax请求 并且保证顺序
queryData('http://localhost:3000/data')
	.then((data)=>{
		console.log(data)
		return queryData('http://localhost:3000/data1')
	})
	.then((data)=>{ // 得到上一步的异步任务的结果
		console.log(data)
		return queryData('http://localhost:3000/data2')
	})
	.then((data)=>{
		console.log(data)
	})

The return value of the function in the then parameter
returns the promise instance object-the returned instance object will call the next then
to return the ordinary value-the returned ordinary value will be passed directly to the next then receive the value through the parameter of the function in the then parameter

Promises commonly used API

// 打印promise的详细信息
console.dir(Promise)
  1. Instance
    method.then () gets the correct result of the asynchronous
    task.catch () gets the exception information.finally
    () will be executed if it succeeds or not

  2. The object method
    Promise.all () processes multiple asynchronous tasks concurrently and all tasks are executed to get results.
    Promise.race () processes multiple asynchronous tasks concurrently as long as one task completes to get results

Second interface call fetch usage

Basic characteristics

  1. The simpler data acquisition method is more powerful and flexible, which can be regarded as an upgraded version of xhr
  2. Implementation based on promise
fetch('http://localhost:3000/data').then(data=>{
	// text()方法属于fetch API的一部分 它返回一个promise实例对象 得到后台返回的数据
	return data.text()
})then(data=>{
	console.log(data)
})

Common parameter configuration of fetch request parameters
method(String) : HTTP request method defaults to GET (GET, POST, PUT, DELETE)
body(String): HTTP request parameters
headers(Object): HTTP request header defaults to {}

GET request

fetch('http://localhost:3000/data?id=1',{method:'get'}).then(data=>{
	return data.text()
})then(data=>{
	console.log(data)
})

GET background interface

app.get('/data',(req,res)=>{
	res.send('传统url传递参数' + req.query.id)
})

DELETE request

fetch('http://localhost:3000/list/1',{method:'delete'}).then(data=>{
	return data.text()
})then(data=>{
	console.log(data)
})

DELETE background interface

app.delete('/list/:id',(req,res)=>{
	res.send('restful形式的url传递参数' + req.params.id)
})

Traditional parameters of POST request

fetch('http://localhost:3000/lists',{
	method:'post',
	body:'uname=lisi&pwd=222',
	headers:{
		'Content-Type':'application/x-www-form-urlencoded'
	}
}).then(data=>{
	return data.text()
})then(data=>{
	console.log(data)
})

POST background interface

app.post('/lists',(req,res)=>{
	res.send('post请求' + req.body.uname + req.body.pwd)
})
// body是由body-parser中间件提供的

POST request json format

fetch('http://localhost:3000/lists',{
	method:'post',
	body:JSON.stringify({
		uname:'lisi',
		pwd:222
	}),
	headers:{
		'Content-Type':'application/json'
	}
}).then(data=>{
	return data.text()
})then(data=>{
	console.log(data)
})

put请求与post请求类似

The fetch response data format
text () processes the return body into a string type
json (). The return result is the same as JSON.parse (responseText). The
json format uses the data format returned by replacing the above text () with json (). Should be in json format

Three interface call axios usage

Basic characteristics of HTTP client based on promise for browser and node.js
:

  1. Support browser and node
  2. Support promise
  3. Ability to intercept requests and responses
  4. Automatically convert JSON data

First download axiospackage

axios.get('http://localhost:3000/data').then(ret=>{
	// data属性是固定的 用于获取后台响应的数据
	console.log(data.ret)
})

Background interface

app.get('/data',(req,res)=>{
	res.send('hello axios')
})

Axios commonly used API
get post put delete

GET pass parameters
pass URL pass parameters
pass params option pass parameters

axios.get('http://localhost:3000/data?id=1').then(ret=>{
	console.log(data.ret)
})

Background interface

app.get('/data',(req,res)=>{
	res.send('axios get传递参数' + req.query.id)
})

You can also restfulparameters of the reference transmission mode fetchof the deletemethod of

params pass parameters

axios.get('http://localhost:3000/data',{
	params:{ // 可以传递多个参数 比较方便
		id:1
	}
}).then(ret=>{
	console.log(data.ret)
})

Background interface

app.get('/data',(req,res)=>{
	res.send('axios get传递参数' + req.query.id)
})

DELETE transfer parameters are similar to GET

POST parameters

默认传递的是JSON格式的数据 需要后台提供支持
axios.post('http://localhost:3000/data',{
	uname:'lisi',
	pwd:222
}).then(ret=>{
	console.log(data.ret)
})

Background interface

app.post('/data',(req,res)=>{
	res.send('axios post传递参数' + req.body.uname + req.body.id)
})
// 通过 URLSearchParams 传递参数 
// 如果后台支持json使用上面那种方法 如果两种都支持还是使用上面那种方法
var params = new URLSearchParams();
params.append('uname', 'lisi')
params.append('pwd', '222')
axios.post('http://localhost:3000/data',params).then(ret=>{
	console.log(data.ret)
})

Background interface

app.post('/data',(req,res)=>{
	res.send('axios post传递参数' + req.body.uname + req.body.id)
})

putThe request is postsimilar to the request

Axios response results
data Actual data returned from
headersresponse Response header information
statusResponse status code
statusTextResponse status information

Global configuration of axios

// 超时时间
axios.defaults.timeout = 5000; 
// 配置请求的基准URL地址
axios.defaults.baseurl = 'http://localhost:3000'
// 请求头信息 
axios.defaults.headers['token'] = 'xxxxx'

axios interceptor
request interceptor configures some information before the request is issued

// 添加请求拦截器 通过拦截器可以控制所有请求
axios.interceptors.request.use(config=>{
	config.headers.token = 'xxx' // 配置请求头
	return config
},err=>{
	console.log(err)
})

The response interceptor does some processing on the data before getting it

// 添加响应拦截器 
axios.interceptors.response.request.use(res=>{
	console.log(res)
	return res
},err=>{
	console.log(err)
})

Four interface calls async / await usage

async / await is a new syntax introduced by ES7 to make asynchronous operations more convenient. The
async keyword is the same as the return value of the
async function on the function. The await keyword of the Promise instance object is used in the async function.

async function queryData(id){
	const ret = await.get('xxxx')
	return ret
}
queryData.then(ret=>{
	console.log(ret)
})

实际项目中的应用场景
Insert picture description here
Handle multiple asynchronous requests

async function queryData(id){
	const info = await axios.get('xxxx1')
	const ret = await.get('xxxx2?info=' + info.data)
	return ret.data
}
queryData.then(data=>{
	console.log(data)
})
Published 41 original articles · Likes2 · Visits 1836

Guess you like

Origin blog.csdn.net/weixin_43883485/article/details/105142491