• Vue学习:axios


    Axios

    1. axios的简介

    1.1 axios是什么

    ​ Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

    • 前端最流行的ajax请求库
    • react/vue官方推荐使用axios发送ajax请求
    • 官方网站: https://www.axios-http.cn/

    1.2 axios特征

    • 从浏览器创建 XMLHttpRequests
    • 从 node.js 创建 http 请求
    • 支持 Promise API
    • 拦截请求和响应
    • 转换请求和响应数据
    • 取消请求
    • 自动转换JSON数据
    • 客户端支持防御[XSRF]

    2. axios的使用

    2.1 axios的API

    • axios(config): 通用的发送任意请求的方式
    • axios(url[, config]): 可以只指定url发送get请求
    • axios.request(config): 等同于axios(config)
    • axios.get(url[, config]): 发送get请求
    • axios.delete(url[, config]): 发送delete请求
    • axios.post(url[, data[, config]]):发送post请求
    • axios.put(url[, data[, config]]): 发送put请求
    • axios.patch(url[, data[, config]]): 发送patch请求
    • axios.head(url[, config])
    • axios.options(url[, config])
    • axios.defults.xxx:请求的默认全局配置
    • axios.interceptors.request.use(): 添加请求拦截器
    • axios.interceptors.response.use(): 添加响应拦截器
    • 有时候, 我们可能需求同时发送两个请求,使用axios.all, 可以放入多个请求的数组.
      axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2

    2.2 常见的配置选项

    • 请求地址

    • 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){ }

    • 请求体

    • data: { key: ‘aa’},

    • 超时设置

    • timeout: 1000,

    2.3 安装axios

    第一种方式: 使用npm

    npm install axios
    
    • 1

    第二种方式: 使用cdn

    <script src="https://unpkg.com/axios/dist/axios.min.js">script>
    
    • 1

    第三种方式: 使用yarn

    yarn add axios
    
    • 1

    2.4 vue3使用axios发送请求

    1. 安装axios插件
    npm install axios 
    
    • 1
    1. 在main.js文件使用axios
    import axios from 'axios'
    const app = createApp(App);
    //使用axios, 并把axios作为app的全局属性
    app.config.globalProperties.$axios=axios;
    app.mount('#app')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. axios发送get请求demo:
    this.$axios.get("https://autumnfish.cn/cloudsearch?keywords=" + this.query)
     				.then(function(response) {
     					console.log(response)
     					that.musicList = response.data.result.songs;
     				}, function(err) {});
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.封装axios的工具

    安装qs

    npm install qs
    
    • 1

    在src目录下创建一个utils目录,用于存放一些工具的js文件, 在这个目录下我们创建一个request.js用于封装axios

    import axios from 'axios'
    import qs from 'qs'
    /**
     * axios的传参方式:
     * 1.url 传参 一般用于Get和Delete 实现方式:config.params={JSON}
     * 2.body传参 实现方式:config.data = {JSON},且请求头为:headers: { 'Content-Type': 'application/json;charset=UTF-8' }
     * 3.表单传参 实现方式:config.data = qs.stringify({JSON}),且请求头为:且请求头为:headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
     */
    // axios实例
    const $http = axios.create({
    	baseURL: '',
    	timeout: 60000,
    	headers: { 'Content-Type': 'application/json;charset=UTF-8' }
    })
     
    // 请求拦截器
    $http.interceptors.request.use(
    	(config) => {
    		// 追加时间戳,防止GET请求缓存
    		if (config.method?.toUpperCase() === 'GET') {
    			config.params = { ...config.params, t: new Date().getTime() }
    		}
    		
    		if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {
    			config.data = qs.stringify(config.data)
    		}
    		return config
    	},
    	error => {
    		return Promise.reject(error)
    	}
    )
     
    // 响应拦截器
    $http.interceptors.response.use(
    	response => {
    		const res = response.data
    		return res
    	},
    	error => {
    		return Promise.reject(error)
    	}
    )
     
    // 导出 axios 实例
    export default $http
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    在main.js中,把$http绑定到app对象上

    // 导入封装好的axios并挂载到Vue全局属性上
    import $http from './utils/request'
    app.config.globalProperties.$http = $http
    
    • 1
    • 2
    • 3

    使用:

     methods: {
            sendAjax(){
                this.$http.get("https://autumnfish.cn/cloudsearch?keywords=" + this.query)
     				.then(function(response) {
     					console.log(response)
     				}, function(err) {});
            }
        },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 相关阅读:
    .\missyou-0.0.1-SNAPSHOT.jar中没有主清单属性
    python学习2
    代码随想录算法训练营第四十二天| 01背包问题,你该了解这些! 01背包问题,你该了解这些! 滚动数组 416. 分割等和子集
    【Python】练习题附带答案
    SpringCloudAlibaba 微服务讲解(三)Nacos Discovery-服务治理
    XSS进阶三
    RabbitMQ安装
    Python速成1——环境搭建与基本数据类型
    什么是Mock?为什么要使用Mock呢?
    2023年中国自动化微生物样本处理系统竞争现状及行业市场规模分析[图]
  • 原文地址:https://blog.csdn.net/H215919719/article/details/127789490