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

Axios基本使用

介绍

Axios 是一个基于promise网络请求库,作用于node.js和浏览器中

特性

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

安装

项目中
npm install axios
yarn add axios
学习阶段
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.min.js"></script>

基本使用

axios({//方法method: "",//urlurl: "",//设置请求体//data: {}
}).then(response => {console.log(response);//...
});

API

axios.request(config)
axios.request({//方法method: "",//urlurl: "",
}).then(response => {console.log(response);//...
});
axios.post(url[, data[, config]])
axios.post("http://....", {"body":"喜大普奔","postId":2
}).then(response => {console.log(response);//...
});
其他
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

axios返回结果

在这里插入图片描述
config:为axios配置项,

data:服务器返回的数据,axios默认做json转换。

headers:http响应头

request: 原生ajax对象

status:状态码

statusText:状态描述

axios 配置对象

这些是用于发出请求的可用配置选项。

{url: '/user',method: 'get', // defaultbaseURL: 'https://some-domain.com/api/',//对请求数据做预先处理transformRequest: [function (data, headers) {// Do whatever you want to transform the datareturn data;}],//对响应数据进行预处理transformResponse: [function (data) {// Do whatever you want to transform the datareturn data;}],// 请求头信息配置headers: {'X-Requested-With': 'XMLHttpRequest'},//发送请求时url后边的参数?id=12345&name=张三params: {ID: 12345,name:"张三"},// `paramsSerializer` is an optional config in charge of serializing `params` 一般用的不多paramsSerializer: {encode?: (param: string): string => { /* Do custom ops here and return transformed string */ }, // custom encoder function; sends Key/Values in an iterative fashionserialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), // mimic pre 1.x behavior and send entire params object to a custom serializer func. Allows consumer to control how params are serialized.indexes: false // array indexes format (null - no brackets, false (default) - empty brackets, true - brackets with indexes)},//第一种data形式,对象形式data: {firstName: 'Fred'},//第一种data形式,字符串形式data:'Country=Brasil&City=Belo Horizonte',//请求时间timeout: 1000,//跨域请求是否把cookie携带过去,false不携带withCredentials: false,responseType: 'json', // defaultresponseEncoding: 'utf8', // default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName: 'XSRF-TOKEN', // default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName: 'X-XSRF-TOKEN', // default...//代理,一般用在nodejs里面proxy: {protocol: 'https',host: '127.0.0.1',// hostname: '127.0.0.1' // Takes precedence over 'host' if both are definedport: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},...
}

设置默认配置

axios.defaults.method = "get";
axios.defaults.baseURL = "https://api.apiopen.top";
axios.defaults.params = {page: 0,size: 5
}
axios.defaults.timeout = 3000
axios({//urlurl: "/api/getHaoKanVideo"
}).then(response => {console.log(response);
});

创建实例对象发送请求

const a1 = axios.create({baseURL: 'https://some-domain.com/api/',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});
const a2 = axios.create({baseURL: 'https://api.apiopen.top',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});
//发送请求
a1({url:"xxxx",method:"get"
}).then(response => {console.log(response);
})

当需要请求不同域名发送不同请求时可以创建实例对象去发送请求。

下面列出了可用的实例方法。指定的配置将与实例配置合并。

axios#request(config)

axios#get(url[, config])

axios#delete(url[, config])

axios#head(url[, config])

axios#options(url[, config])

axios#post(url[, data[, config]])

axios#put(url[, data[, config]])

axios#patch(url[, data[, config]])

axios#getUri([config])

拦截器

拦截器其实是一些函数,可以在请求和响应之前处理数据、权限判断等。

//请求拦截器
axios.interceptors.request.use(function (config) {//可以对config进行设置throw ("error")//return config;
}, function (error) {return Promise.reject(error);
});//响应拦截器
axios.interceptors.response.use(function (response) {//可以对response进行处理return response;
}, function (error) {return Promise.reject(error);
});axios({method:"get",url: "http://localhost:3300/api/getHaoKanVideo"
}).then(response => {console.log(response);
});

如果请求拦截器抛出异常,那么响应拦截器执行use中第二个参数回调方法。

请求拦截器执行顺序与响应拦截器不同:

axios.interceptors.request.use(function (config) {console.log("请求拦截器-1")return config;
}, function (error) {return Promise.reject(error);
});
axios.interceptors.request.use(function (config) {console.log("请求拦截器-2")return config;
}, function (error) {return Promise.reject(error);
});//响应拦截器
axios.interceptors.response.use(function (response) {console.log("请求拦截器-1")return response;
}, function (error) {return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {console.log("请求拦截器-2")
}, function (error) {return Promise.reject(error);
});axios.defaults.method = "get";
axios.defaults.baseURL = "https://api.apiopen.top";
axios.defaults.params = {page: 0,size: 5
}
axios({//urlurl: "/api/getHaoKanVideo"
}).then(response => {console.log("执行结果-3")console.log(response);
});

执行的结果为:
在这里插入图片描述
请求拦截器后加入的会先执行。

http://www.dtcms.com/a/298315.html

相关文章:

  • JS逆向 - (国外)SHEIN站 - 请求头(armorToken、Anti-in)
  • 【05】C#入门到精通——C# 面向对象、类、静态变量static、类与类之间的调用
  • [SV]在 Verilog 中,对某个信号施加一个弱下拉,但又不能影响后续的正常驱动
  • CSS 盒子模型学习版的理解
  • 【论文阅读51】-CNN-LSTM-安全系数和失效概率预测
  • Multiscale Structure Guided Diffusion for Image Deblurring 论文阅读
  • 【论文阅读】-《GenAttack: Practical Black-box Attacks with Gradient-Free Optimization》
  • 零售收银系统开源代码全解析:连锁门店一体化解决方案(含POS+进销存+商城)
  • 深入理解 Linux 进程信号
  • Linux 桌面市场份额突破 5%:开源生态的里程碑与未来启示
  • [MMU]四级页表查找(table walk)的流程
  • 流式接口,断点续传解决方案及实现
  • 前端核心进阶:从原理到手写Promise、防抖节流与深拷贝
  • iOS 抓包工具有哪些?模块化功能解析与选型思路
  • 容器化环境下的服务器性能瓶颈与优化策略
  • ubuntu22.04.4锁定内核应对海光服务器升级内核无法启动问题
  • Qt Mysql linux驱动编译
  • Google AI Mode 解析:生成式搜索功能的核心机制与应用场景
  • PowerDesigner安装教程(附加安装包)PowerDesigner详细安装教程PowerDesigner 16.6 最新版安装教程
  • Nacos-服务注册,服务发现(一)
  • 【模型剪枝1】结构化剪枝论文学习笔记
  • 如何理解SpringBoot starters的自动装配
  • 地下隧道管廊结构健康监测系统 测点的布设及设备选型
  • 1 51单片机-C51语法
  • 4麦 360度定位
  • docker搭建ray集群
  • SAP-PP-MRPLIST
  • MybatisPlus-17.扩展功能-JSON处理器
  • 【57】MFC入门到精通——MFC 多线程编程总结
  • 【lucene】自定义tokenfilter 自带payload