当前位置: 首页 > news >正文

Axios

1. axios的简介

1.1 axios是什么

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

  • 前端最流行的ajax请求库

  • react/vue官方推荐使用axios发送ajax请求

  • 官方网站: Axios中文文档 | Axios中文网

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 
  2. 在main.js文件使用axios

    import axios from 'axios'
    const app = createApp(App);
    //使用axios, 并把axios作为app的全局属性
    app.config.globalProperties.$axios=axios;
    app.mount('#app')
  3. 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) {});this.$axios.get("https://autumnfish.cn/api/joke/list?num=10").then(function(response){// console.log(response)console.log(response.data);console.log(that.joke);that.joke = response.data;},function (err) {  }) 

跨域请求:默认不支持跨域请求

解决客户端跨域问题:
解决客户端跨域问题:
devServer: {host: 'localhost',  // 此前端项目的IP地址port: 8080,  // 此前端项目的端口号open: true,  //表示在启动开发服务器时,会自动打开浏览器并访问指定的地址proxy: {'/api': {target: 'https://www.kuaikanmanhua.com/', //接口域名changeOrigin: true,       //是否跨域ws: true,            //是否代理 websocketssecure: true,          //是否https接口pathRewrite: {'^/api': ''  //假如我们的地址是 /api/member/getToken 会转化为 /member/getToken}}}}
//服务端的跨域请求@CrossOrigin@GetMapping("{currentPage}/{pageSize}")public ResponseData<Page<User>> getPage(@PathVariable int currentPage, @PathVariable int pageSize, UserConditionVO userConditionVO){Page<User> page = userService.getPage(currentPage,pageSize, userConditionVO);return ResponseDataUtil.buildOk(page);}

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.datareturn 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) {});}},

http://www.mrgr.cn/news/36261.html

相关文章:

  • JavaScript的执行上下文和执行栈
  • Spring 的依赖注入原理
  • 【裸机装机系列】15.kali(ubuntu)-重装linux步骤
  • 使用openpyxl轻松操控Excel文件
  • Pandas和Seaborn可视化详解
  • PLC Twincat3 对传感器数据滑动平均滤波
  • 微软宣布弃用WSUS,企业用户尽早准备替换方案
  • javase复习day33网络编程
  • Spring Boot 中实现动态列导入讲解和案例示范
  • JPA+Thymeleaf
  • 《Detection of Tea Leaf Blight in Low-Resolution UAV Remote Sensing Images》论文阅读
  • [java][git]git学习
  • LocalStorage
  • Java面向对象(二)(类的方法)(自己学习整理的资料)
  • 2-103 基于matlab的光电信号下血氧饱和度计算
  • nginx部署手册
  • Linux 系统安全工具简介
  • 【机器学习】Flux.jl 生态
  • 静电势能(electrostatic potential energy)和电势(electric potential)
  • Windows (rust) vulkan 画一个三角形: 窗口创建与渲染初始化