axios

1. axios的基础用法

一个基于Promise 用于浏览器和 node.js的HTTP客户端
特征

  • 支持浏览器和node.js
  • 支持 promise
  • 能拦截请求和响应
  • 自动转换 JSON 数据
1.1 get 传递参数
  • 通过传统的url 以 ? 的形式传递参数

  • restful 形式传递参数

  • 通过params 形式传递参数

axios.get('http://localhost:3000/adata').then(function(ret){
	#拿到 ret 是一个对象 所有的对象都存在 ret 的data 属性里面
      // 注意data属性是固定的用法,用于获取后台的实际数据
	console.log(ret.data)
})
	# 2.  get 请求传递参数
    # 2.1  通过传统的url  以 ? 的形式传递参数
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
	console.log(ret.data)
})
	# 2.3  通过params  形式传递参数 
axios.get('http://localhost:3000/axios',{
	params:{
		id: 789
	}
}).then(function(ret){
	console.log(ret.data)
})
1.2 delete 传递参数

与get请求类似传参写法

axios.delete('',{
    params:{
        id:123
    }
}).then(ret=>{
    console.log(ret.data);
})
1.3 post 请求
  • 通过选项传递参数(默认传递的是json格式的数据)
axios.post('/adata',{
    uname:'lisi',
    pwd:123
}).then(function(ret){
    console.log(ret.data)
})
  • 通过URLSearchParams传递参数(application/x-www-form-urlencoded表单格式)
var params = new URLSearchParams();
params.append('uname', 'lisi');
params.append('pwd', '123');
axios.post('http://localhost:3000/axios', params).then(function (ret) {
    console.log(ret.data);
})
1.4 put 请求传参

和post一样

axios.put('http://localhost:3000/axios/123',{
    uname:'lisi',
    pwd:123
}).then(function(ret){
    console.log(ret.data)
})
1.5 axios响应结果
  • data:实际响应回来的数据
  • headers:响应头信息
  • status:响应状态码
  • statusText:响应状态信息
axios.post('http://cymdev.piccmall.cn:4445/sys/auth/login/local/getUserPhone?userId=zhangxue').then(function (ret) {
            console.log(ret);
        })
// 打印数据:
config: {transitional: {}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ,}
data: {success: true, msg: null, code: '200', details: null, data: '04debf23ef7fd506596a184dfc300aa16fb98ce3943ab9976d…aa18a40892c41db5241a2b604f5dfe6f4c61edb074a0ca827'}
headers: {cache-control: 'no-cache, no-store, max-age=0, must-revalidate', content-type: 'application/json', expires: '0', pragma: 'no-cache'}
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,}
status: 200
statusText: ""
1.6 axios全局配置
  • axios.defaults.timeout = 3000; // 超时时间
  • axios.defaults.baseURL = ‘http://localhost:3000/app’; //默认地址
  • axios.defaults.headers[‘mytoken’] = ‘aqwerwqwerqwer2akjdkj’ //设置请求头
// 配置请求的基准URL地址
axios.defaults.baseURL = 'http://localhost:3000/';
axios.post('getUserPhone').then(function (ret) {
     console.log(ret);
})

2. axios请求拦截器/响应拦截器

2.1 html中使用拦截器

先引入axios.js文件再进行拦截器使用

<body>
    <script src="./js/axios.js"></script>
    <script>
        // axios请求拦截器
        axios.interceptors.request.use(function (config) {
            // 在请求发出之前进行一些信息设置
            config.headers.mytoken = 'nihao';
            return config;
        }, function (err) {
            // 处理响应的错误信息
            console.log(err);
        })

        // axios响应拦截器
        axios.interceptors.response.use(function(res) {
            // 在这里对返回的数据进行处理
            var data = res.data;
            return data;
        }, function (err) {
            console.log(err);
        })    axios.post('http://cymdev.piccmall.cn:4445/sys/auth/login/local/getUserPhone?userId=zhangxue').then(function (ret) {
            console.log(ret);//ret 为响应拦截器处理返回的数据
        })
    </script>
</body>
2.2 vue项目中使用拦截器

1.导入axios

import axios from 'axios'

2.配置请求的根路径

axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'

3.给vue原型添加一个属性
$http为axios对象,就可以在任意的vue界面中通过this.$http发起axios请求 例如this.$http.post()发起post请求

Vue.prototype.$http = axios

4.设置axios请求拦截器

axios.interceportors.request.use(config=>{
    // 显示进度条
    Nprogress.start()
    // 把请求头添加到Authorization上
    config.headers.Authorization = 	window.sessionStorage.getItem('token')
	//在最后必须 return config
    return config
})

5.设置axios响应拦截器

axios.interceptors.response.use(config=>{
    //隐藏进度条
    Nprogress.done()
    return config
})
2.3 axios设置请求超时时间timeout
  1. axios全局设置网络超时

    axios.defaults.timeout = 30*1000; //30s
    
  2. 单独对某个请求设置网络超时

    axios.post(url,params,{timeout:1000})
       .then(res=>{
        console.log(res);
    })
       .catch(err=>{
        console.log(err);
    })
    

例子:60s之后该请求自动取消

import axios from 'axios';
const comVideoInfo = (options = {},) => {
    return axios.post(
        '/security/user/comprehensiveVideoInfoValidate',
        options,
        { timeout: 60000 }
    );
};
export default comVideoInfo;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值