axios由浅入深(一)

axios

构建服务端json-server

  1. 安装全局json-server
npm install -g json-server
  1. 创建一个db.json
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
  1. 开启json-server服务
json-server --watch db.json
  1. 浏览器输入以下即可看到自己的json数据
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
  1. 演示效果

在这里插入图片描述

axios是什么?

  1. 前端最流行的ajax请求库
  2. 基于Promise的http客户端,可以在node.js和浏览器中运行
  3. 在浏览器端,可以借助axios向服务端发送Ajax请求来获取数据
  4. 可以在node.js端运行,向远端服务器发送http请求

axios特点:

  1. 请求响应拦截器
  2. 对请求和响应数据做转换

安装axios:

  1. 使用npm安装
npm install axios
  1. 使用yarn安装
yarn add axios
  1. 使用jsDelivr CDN引入
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

  1. 使用unpkg CDN引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  1. 使用国内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:

  1. url:设置请求url
  2. method:设置请求类型
  3. baseURL:设置url的基础结构地址
  4. transformRequest:对请求的数据做处理,处理后将结果发送至服务器
  5. transformResponse:对响应的结果做一些改变
  6. headers:对请求头信息作相应的控制
  7. params:用来设定url参数
  8. paramsSerializer:参数序列化的配置,对请求参数作序列化的操作,转换成字符串

axios默认配置:

  1. axios.defaults.methods = 'GET' // 设置请求默认的类型为GET
    
  2. axios.defaults.baseURL = 'http://localhost:3000/' // 设置基础URL
    
  3. axios.defaults.params = {id: 100} // 默认将id=100加到请求url上
    
  4. 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

在这里插入图片描述

看到这里,axios基本使用就应该掌握的差不多了,下一篇深入研究axios源码并模拟实现,感谢观看!

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Y shǔ shǔ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值