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

第二种方式: 使用cdn

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

第三种方式: 使用yarn

yarn add axios

2.4 vue3使用axios发送请求

  1. 安装axios插件
npm install axios 
  1. 在main.js文件使用axios
import axios from 'axios'
const app = createApp(App);
//使用axios, 并把axios作为app的全局属性
app.config.globalProperties.$axios=axios;
app.mount('#app')
  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) {});

3.封装axios的工具

安装qs

# npm安装
npm install qs
# yarn 安装
yarn add qs

在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

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

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

使用:

 methods: {
        sendAjax(){
            this.$http.get("https://autumnfish.cn/cloudsearch?keywords=" + this.query)
 				.then(function(response) {
 					console.log(response)
 				}, function(err) {});
        }
    },
  • 26
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值