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

相关文章:

  • 分别使用 Java 8 和 Python 调用 Elasticsearch 接口简单获取数据
  • Web前端:JavaScript 随机点名系统案例详解
  • 常用设计模式系列(十二)—享元模式
  • OpenTelemetry学习笔记(十二):在APM系统中,属性的命名空间处理遵循规则
  • 基于讯飞星火AI的文学作品赏析系统开发实战:从通用聊天到专业文学分析的完整技术方案
  • 新房装修是中央空调还是壁挂空调好?
  • 滑动窗口---6(稍难)
  • GDB调试命令学习
  • 【开源软件】SimpleAI一款轻量级的桌面随身AI助手
  • 航段导航计算机 (Segment_Navigator) 设计与实现
  • OSPF 协议(多区域)
  • Python智能优化算法实战指南
  • 汪小菲食通达公司成立新零售公司,布局餐饮零售新赛道
  • 轻量级音乐元数据编辑器Metadata Remote
  • SpringBoot整合Liquibase提升数据库变更的可控性、安全性、自动化程度(最详细)
  • 自动化UI测试工具TestComplete的AI双引擎:即时数据集 + 自愈测试
  • SpringBoot学习路径二--Spring Boot自动配置原理深度解析
  • Qt 多媒体开发:音频与视频处理
  • 剪映将绿幕视频扣成透明背景视频转webm格式可以在网页上透明播放
  • 软件工程之可行性研究:从理论到实践的全面解析
  • SpringBoot 集成Mybatis Plus
  • ESLint前端工程实践
  • CMake保姆级教程
  • 力扣1472. 设计浏览器历史记录
  • Execel文档批量替换标签实现方案
  • 三维图像识别中OpenCV、PCL和Open3D结合的主要技术概念、部分示例
  • 【vue3+vue-pdf-embed】实现PDF+图片预览
  • Ubuntu22 上,用C++ gSoap 创建一个简单的webservice
  • 前端学习9:JavaScript--对象与原型
  • vue3 组件生命周期,watch和computed