定义
Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js中。Axios(相比于原生的XMLHttpRequest对象来说) 简单易用,(相比于jQuery)axios包尺寸小且提供了易于扩展的接口,是专注于网络请求的库。
请求的方法
get:获取数据,请求制定的信息,返回实体对象
post:向指定资源提交数据(例如表单提交或文件上传)
put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
delete:请求服务器删除指定的数据
head:获取报文首部
如何安装
- 使用npm安装
npm install axios
- 使用unpke CDN
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.2.0/axios.min.js"></script>
使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.2.0/axios.min.js"></script>
<script>
//1.axios:带请求体
const bookInfo =
{
bookname: "如何三块钱活一天",
author: "小明",
publisher: "未知名出版社"
}
axios({
url: "http://hmajax.itheima.net/api/books",
method: "POST",
data: {
...bookInfo,
creator: "老张"
}
}).then(result => {
//请求成功返回数据
console.log(result)
}).catch(error => {
//请求错误返回结果
console.log(error)
})
//2.axios:带参数查询
//method:默认为GET
axios({
url: 'http://hmajax.itheima.net/api/books',
method: 'GET',
params: {
// 外号:获取对应数据
creator
}
}).then(result => {
//请求成功返回数据
console.log(result)
}).catch(error => {
//请求错误返回结果
console.log(error)
})
//3.axios:FormData,上传文件或图片
//使用 FormData 携带图片文件
const fd = new FormData()
//参数属性名称img,属性值 e.target.files[0],根据后端接口文档写
fd.append('img', e.target.files[0])
axios({
url: 'http://hmajax.itheima.net/api/uploadimg',
method: 'POST',
data: fd
}).then(result => {
console.log(result)
})
</script>
</body>
</html>
自行封装
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="reg-btn">注册用户</button>
<script>
function axiosHelper(configs) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
const endUrl = configs.params && `+?${new URLSearchParams(configs.params).toString()}`
configs.url = endUrl ? (configs.url + endUrl) : configs.url
xhr.open(configs.method || 'GET', configs.url)
xhr.addEventListener('loadend', () => {
if (xhr.status >= 200 && xhr.status < 300) {
//请求成功
resolve(JSON.parse(xhr.response))
} else {
//错误
reject(new Error(xhr.response))
}
})
//有请求体
if (configs.data) {
const jsonStr = JSON.stringify(configs.data)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(jsonStr)
}
else {
xhr.send()
}
})
}
//使用axiosHelper函数,完成注册用户
document.querySelector('.reg-btn').addEventListener('click', () => {
axiosHelper({
url: 'http://hmajax.itheima.net/api/register',
method: 'POST',
data: {
username: 'itheima999',
password: '666666'
}
}).then(result => {
console.log(result)
}).catch(error => {
console.dir(error)
})
})
</script>
</body>
</html>