axios学习笔记

axios

npm install axios --save

http://httpbin.org/

http://123.207.32.32:8000/home/multidata

http://123.207.32.32:8000/home/data?type=sell&page=1

Vue中发送网络请求有非常多的方式, 那么, 在开发中, 如何选择呢?

  • 选择一: 传统的Ajax是基于XMLHttpRequest(XHR)

    • 为什么不用它呢?
      • 非常好解释, 配置和调用方式等非常混乱.
      • 编码起来看起来就非常蛋疼.
      • 所以真实开发中很少直接使用, 而是使用jQuery-Ajax
  • 选择二: 在前面的学习中, 我们经常会使用jQuery-Ajax
    相对于传统的Ajax非常好用.

    • 为什么不选择它呢?
      • 首先, 我们先明确一点: 在Vue的整个开发中都是不需要使用jQuery了.
      • 那么, 就意味着为了方便我们进行一个网络请求, 特意引用一个jQuery, 你觉得合理吗?
      • jQuery的代码1w+行.
      • Vue的代码才1w+行.
      • 完全没有必要为了用网络请求就引用这个重量级的框架.
  • 选择三: 官方在Vue1.x的时候, 推出了Vue-resource.

    Vue-resource的体积相对于jQuery小很多.
    另外Vue-resource是官方推出的.

    • 为什么不选择它呢?
    • 在Vue2.0退出后, Vue作者就在GitHub的Issues中说明了去掉vue-resource, 并且以后也不会再更新.
    • 那么意味着以后vue-reource不再支持新的版本时, 也不会再继续更新和维护.
    • 对以后的项目开发和维护都存在很大的隐患.
  • 选择四: 在说明不再继续更新和维护vue-resource的同时, 作者还推荐了一个框架: axios
    axios有非常多的优点, 并且用起来也非常方便.

jsonp

  • 在前端开发中, 我们一种常见的网络请求方式就是JSONP
  • 使用JSONP最主要的原因往往是为了解决跨域访问的问题.
    • JSONP的原理是什么呢?
      • JSONP的核心在于通过

image-20220705090654925

image-20220705090746429

image-20220705090823031

axios特点

  • 在浏览器中发送 XMLHttpRequests 请求
  • 在 node.js 中发送 http请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据

支持多种请求方式:

  • axios(config)
  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

发送get请求

axios({
  url: 'http://123.207.32.32:8000/home/multidata',
  method: 'get' // 默认是get请求
}).then(res => {
  console.log(res)
})

image-20220705092850949

axios.get('http://123.207.32.32:8000/home/data',
  {params: { type: 'shell', page: 1}})
    .then(res => {
      console.log(res)
  })

使用axios.all, 可以放入多个请求的数组.
axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2

axios.all([axios.get('http://123.207.32.32:8000/home/multidata'),axios.get('http://123.207.32.32:8000/home/data',
  {params: {type: 'shell', page: 1}})
]).then(axios.spread((res1, res2) =>{
  console.log(res1)
  console.log(res2)
}))

全局配置

axios.defaults.baseURL =123.207.32.32:8000’
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;
axios.defaults.baseURL = "http://123.207.32.32:8000"

axios.all([axios.get('/home/multidata'),axios.get('/home/data',
  {params: {type: 'shell', page: 1}})
]).then(axios.spread((res1, res2) =>{
  console.log(res1)
  console.log(res2)
}))
  • 请求地址
    url: ‘/user’,
  • 请求类型
    method: ‘get’,
  • 请根路径
    baseURL: ‘http://www.mt.com/api’,
  • 请求前的数据处理
    transformRequest:[function(data){}],
  • 请求后的数据处理
    transformResponse: [function(data){}],
  • 自定义的请求头
    headers:{‘x-Requested-With’:‘XMLHttpRequest’},
  • URL查询对象
    params:{ id: 12 },
  • 查询对象序列化函数
    paramsSerializer: function(params){ }
    request body
    data: { key: ‘aa’},
  • 超时设置s
    timeout: 1000,
  • 跨域是否带Token
    withCredentials: false,
  • 自定义请求处理
    adapter: function(resolve, reject, config){},
  • 身份验证信息
    auth: { uname: ‘’, pwd: ‘12’},
  • 响应的数据格式 json / blob /document /arraybuffer / text / stream
    responseType: ‘json’,

axios实例

  • 为什么要创建axios的实例呢?
    • 当我们从axios模块中导入对象时, 使用的实例是默认的实例.
    • 当给该实例设置一些默认配置时, 这些配置就被固定下来了.
    • 但是后续开发中, 某些配置可能会不太一样.
    • 比如某些请求需要使用特定的baseURL或者timeout或者content-Type等.
    • 这个时候, 我们就可以创建新的实例, 并且传入属于该实例的配置信息.
// 创建新的实例
const axiosInstance = axios.create({
  baseURL: 'http://123.207.32.32:8000',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

axiosInstance({
  url:'/home/multidata',
  method: 'get'
}).then(res => {
  console.log(res)
}).catch(err => {
  console.log(err)
})

axios封装

src->network->request.js

import axios from 'axios'

export function request(config) {
    // 1.创建axios的实例
    const instance = axios.create({
        baseURL: 'http://123.207.32.32:8000',
        timeout: 5000,
    })

    // 2.axios的拦截器
    // 2.1请求拦截的作用
    // 发送真正的网络请求
    instance.interceptors.request.use(config => {
         // console.log(config);
        // 1.比如config中的一些信息不符合服务器的要求

        // 2.比如每次发送网络请求时, 都希望在界面中显示一个请求的图标

        // 3.某些网络请求(比如登录(token)), 必须携带一些特殊的信息
        return config
    }, err => {
        console.log(err)
    })
    // 2.2响应拦截
    instance.interceptors.response.use(res => {
        return res.data
    }, err => {
        console.log(err)
    })
    // 3.发送真正的网络请求
    return instance(config)
}

main.js

import {request} from './network/request'

request({
  url: '/home/multidata'
})
.then(res => {
  console.log(res)
})
.catch(err => {
  console.log(err)
})

拦截器

image-20220705134025390

js

import {request} from './network/request'

request({
  url: '/home/multidata'
})
.then(res => {
  console.log(res)
})
.catch(err => {
  console.log(err)
})

拦截器

[外链图片转存中…(img-x4QwoH7i-1657019343794)]

image-20220705134102544

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

爱写bug的小邓程序员

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

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

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

打赏作者

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

抵扣说明:

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

余额充值