axios
构建服务端json-server
- 安装全局json-server
npm install -g json-server
- 创建一个db.json
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
- 开启json-server服务
json-server --watch db.json
- 浏览器输入以下即可看到自己的json数据
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
- 演示效果
axios是什么?
- 前端最流行的ajax请求库
- 基于Promise的http客户端,可以在node.js和浏览器中运行
- 在浏览器端,可以借助axios向服务端发送Ajax请求来获取数据
- 可以在node.js端运行,向远端服务器发送http请求
axios特点:
- 请求响应拦截器
- 对请求和响应数据做转换
安装axios:
- 使用npm安装
npm install axios
- 使用yarn安装
yarn add axios
- 使用jsDelivr CDN引入
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
- 使用unpkg CDN引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- 使用国内bootcdn引入(推荐)
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
axios的基本使用:
axios发送get请求
<script>
// 获取按钮
const btns = document.querySelectorAll('button')
// 第一个按钮
btns[0].onclick = function() {
// 发送Ajax请求
axios({
// 请求类型
method: 'GET',
// url
url: 'http://localhost:3000/posts/1'
}).then(response => {
console.log(response)
})
}
</script>
axios发送post请求
<script>
// 获取按钮
const btns = document.querySelectorAll('button')
// 第二个按钮
btns[1].onclick = function() {
// 发送Ajax请求
axios({
// 请求类型
method: 'POST',
// url
url: 'http://localhost:3000/posts',
// 设置请求体
data: {
title: '这是一个post请求',
author: '张三'
}
}).then(response => {
console.log(response)
})
}
</script>
发送完成后打开我们的db.json就可以看到新加入的data信息
axios发送put请求更新id为2的数据
<script>
// 获取按钮
const btns = document.querySelectorAll('button')
// 第三个按钮
btns[2].onclick = function() {
// 发送Ajax请求
axios({
// 请求类型
method: 'PUT',
// url
url: 'http://localhost:3000/posts/2',
// 设置请求体
data: {
title: '这是一个put请求',
author: '李四'
}
}).then(response => {
console.log(response)
})
}
</script>
这是更新后的数据
axios发送delete请求删除id为2的数据
<script>
// 获取按钮
const btns = document.querySelectorAll('button')
// 第四个按钮
btns[3].onclick = function() {
// 发送Ajax请求
axios({
// 请求类型
method: 'delete',
// url
url: 'http://localhost:3000/posts/2',
}).then(response => {
console.log(response)
})
}
</script>
axios其他使用方式
axios使用request方式发送get请求
<script>
// 获取按钮
const btns = document.querySelectorAll('button')
// 第一个按钮
btns[0].onclick = function() {
// 发送GET请求
axios.request({
method: 'GET',
url: 'http:localhost:3000/comments'
}).then(response => {
console.log(response)
})
}
</script>
axios使用post方式发送请求
<script>
// 获取按钮
const btns = document.querySelectorAll('button')
// 第二个按钮
btns[1].onclick = function() {
// 发送POST请求 三个参数 第一参数:配置请求地址 第二个参数:配置请求参数 第三个参数:诶之请求对象
axios.post('http://localhost:3000/comments',{
'body': '文章的评论',
'postId': 2
}).then(response => {
console.log(response)
})
}
</script>
axios响应参数
config:配置对象,包含了请求类型,请求url,请求体等等
data:响应体的结果,服务器返回的数据
headers:响应头信息
request:原生的ajax请求对象,也就是XMLHttpRequest实例对象
status:响应状态码
statusText:响应状态字符串
axios配置对象config:
- url:设置请求url
- method:设置请求类型
- baseURL:设置url的基础结构地址
- transformRequest:对请求的数据做处理,处理后将结果发送至服务器
- transformResponse:对响应的结果做一些改变
- headers:对请求头信息作相应的控制
- params:用来设定url参数
- paramsSerializer:参数序列化的配置,对请求参数作序列化的操作,转换成字符串
axios默认配置:
-
axios.defaults.methods = 'GET' // 设置请求默认的类型为GET
-
axios.defaults.baseURL = 'http://localhost:3000/' // 设置基础URL
-
axios.defaults.params = {id: 100} // 默认将id=100加到请求url上
-
axios.defaults.timeout = 3000 // 设置超时时间
axios创建实例对象发送ajax请求
const joke = axios.create({
baseUrl: 'https://api.apiopen.top',
timeout: 2000
})
joke({
url: '/getJokes'
}).then(response => {
console.log(response)
})
// 也可以通过实例对象.get方式发送
joke.get('/getJoke').then(response => {
console.log(response)
})
axios拦截器
<script>
// 设置请求拦截器
axios.interceptors.request.use(function (config){
console.log('请求拦截器 成功')
return config
}, function (error) {
console.log('请求拦截器 失败')
return Promise.reject(error)
})
// 设置响应拦截器
axios.interceptors.response.use(function (response){
console.log('响应拦截器 成功')
return response
}, function (error) {
console.log('响应拦截器 失败')
return Promise.reject(error)
})
axios({
methods: 'GET',
url: 'http:localhost:3000/posts'
}).then(response => {
console.log(response)
})
</script>
<script>
// 设置请求拦截器
axios.interceptors.request.use(function (config){
console.log('请求拦截器 成功')
throw '参数出了问题'
}, function (error) {
console.log('请求拦截器 失败')
return Promise.reject(error)
})
// 设置响应拦截器
axios.interceptors.response.use(function (response){
console.log('响应拦截器 成功')
return response
}, function (error) {
console.log('响应拦截器 失败')
return Promise.reject(error)
})
axios({
methods: 'GET',
url: 'http:localhost:3000/posts'
}).then(response => {
console.log('自定义成功回调')
}).catch(reason => {
console.log('自定义失败回调')
})
</script>
如果有多个请求拦截器和响应拦截器,那么请求拦截器后进先执行,响应拦截器先进先执行
axios取消请求
<script>
// 获取按钮
const btns = document.querySelectorAll('button')
// 2. 声明全局变量
let cancel = null
btns[0].onclick = function(){
// 检测上一侧的请求是否完成
if(cancel !== null){
// 表明上一次的请求还在继续,没有完成,所以取消上一次的请求,只执行最后一次请求
cancel()
}
axios({
methods: 'GET',
url: 'http:localhost:3000/posts',
// 1.添加配置对象的属性
cancelToken: new axios.CancelToken(function(c) {
// 3. 将c的值赋值给cancel
cancel = c
})
}).then(response => {
console.log(response)
cancel = null
})
}
btns[1].onclick = function() {
cancel()
}
</script>
为了演示看的清楚,这里设置服务器json-server延时两秒后返回数据
json-server --watch db.json -d 2000