当前位置: 首页 > 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.xdnf.cn/news/1184545.html

相关文章:

  • GUI界面已经移植完,添加欠缺字,微调GUI界面说明
  • Kafka运维实战 15 - kafka 重设消费者组位移入门和实战【实战】
  • 时间和空间复杂度
  • 八股文之JVM
  • DNS 服务正反向解析与 Web 集成实战:从配置到验证全流程
  • Day 21: 常见的降维算法
  • 专题:2025电商增长新势力洞察报告:区域裂变、平台垄断与银发平权|附260+报告PDF、原数据表汇总下载
  • 小米8(dipper)刷入kernelSU内核root定制rom系统教程以及安装LSPosed模块
  • Windows-WSL-Docker端口开放
  • FunASR实时多人对话语音识别、分析、端点检测
  • NLP验证自动化脚本优化
  • 从热点到刚需:SmartMediaKit为何聚焦B端视频系统建设?
  • 【lucene】AttributeSource概述
  • Ethereum:Geth + Clef 本地开发环境,如何优雅地签名并发送一笔以太坊交易?
  • Linux 内存深度剖析:栈与堆的底层机制与实战指南
  • 汽车免拆诊断案例 | 2010款奔驰E200 CGI车EPS OFF灯异常点亮
  • MCP 与传统集成方案深度对决:REST API、GraphQL、gRPC 全方位技术解析
  • Linux725 磁盘阵列RAID0 RAID1
  • Linux库——库的制作和原理(1)_回顾动静态库、制作使用库
  • docker-compose:未找到命令的检查步骤和修复
  • 从数据孤岛到融合共生:KES V9 2025 构建 AI 时代数据基础设施
  • 65.第二阶段x64游戏实战-替换游戏lua打印可接任务
  • 【论文阅读】-《GenAttack: Practical Black-box Attacks with Gradient-Free Optimization》
  • 人工智能概述
  • 智慧电视:开启养老新时代
  • Linux 设备驱动模型
  • LLM:Day3
  • 计算机算术4-整形乘法
  • UE5多人MOBA+GAS 30、技能升级机制
  • Android补全计划 DrawerLayout使用