axios
介绍:#
-
基于promise用于浏览器和node.js的http客户端
-
支持浏览器和node.js
-
支持promise
-
能拦截请求和响应
-
自动转换JSON数据
-
能转换请求和响应数据
基本用法:#
axios.get('http://localhost:3000/adata').then(function(ret){ // 注意data属性是固定的用法,用于获取后台的实际数据 // console.log(ret.data) console.log(ret) })
axios请求参数传递:#
-
get和 delete请求传递参数
-
通过传统的url 以 ? 的形式传递参数
-
restful 形式传递参数
-
通过params 形式传递参数
-
-
post 和 put 请求传递参数
-
通过选项传递参数
-
通过 URLSearchParams 传递参数
-
// axios get请求传参 axios.get('http://localhost:3000/axios?id=123').then(function (ret) { console.log(ret.data) }) axios.get('http://localhost:3000/axios/123').then(function (ret) { console.log(ret.data) }) axios.get('http://localhost:3000/axios', { params: { id: 789 } }).then(function (ret) { console.log(ret.data) }) // axios delete 请求传参 axios.delete('http://localhost:3000/axios', { params: { id: 111 } }).then(function (ret) { console.log(ret.data) }) // axios post 请求传参 axios.post('http://localhost:3000/axios', { uname: 'lisi', pwd: 123 }).then(function (ret) { console.log(ret.data) }) var params = new URLSearchParams(); params.append('uname', 'zhangsan'); params.append('pwd', '111'); axios.post('http://localhost:3000/axios', params).then(function (ret) { console.log(ret.data) }) // axios put 请求传参 axios.put('http://localhost:3000/axios/123', { uname: 'lisi', pwd: 123 }).then(function (ret) { console.log(ret.data) })
axios 与全局配置:#
# 配置公共的请求头 axios.defaults.baseURL = 'https://api.example.com'; # 配置 超时时间 axios.defaults.timeout = 2500; # 配置公共的请求头 axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; # 配置公共的 post 的 Content-Type axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios拦截器:#
-
请求拦截器
-
请求拦截器的作用是在请求发送前进行一些操作
-
例如在每个请求体里加上token,统一做了处理如果以后要改也非常容易
-
-
-
响应拦截器
-
响应拦截器的作用是在接收到响应后进行一些操作
-
-
# 1. 请求拦截器 axios.interceptors.request.use(function(config) { console.log(config.url) # 1.1 任何请求都会经过这一步 在发送请求之前做些什么 config.headers.mytoken = 'nihao'; # 1.2 这里一定要return 否则配置不成功 return config; }, function(err){ #1.3 对请求错误做点什么 console.log(err) }) #2. 响应拦截器 axios.interceptors.response.use(function(res) { #2.1 在接收响应做些什么 var data = res.data; return data; }, function(err){ #2.2 对响应错误做点什么 console.log(err) })
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2019-08-21 基本查询语句及方法、group by 分组、聚合函数、having、distinct去重、order by 排序、limit、正则、多表查询(连表查询、子查询)