vue2【axios请求】

1:axios作用

axios(发音:艾克c奥斯)是前端圈最火的,专注于数据请求的库。

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中axios的github:https://github.com/axios/axios

中文官网地址:http://www.axios-js.com/

英文官网地址:https://www.npmjs.com/package/axios

1.1:引入axios

首先就是引入axios,如果你使用es6,只需要安装axios模块之后

当然也可以用script引入

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2:axios的基础语法

2.1:发起get请求示例

get请求传参的两种方式

第一种拼接路径上面,第二种将参数写在params内

//通过给定的ID来发送请求
axios.get('/user?ID=12345').then(function(response){
        console.log(response);
    }).catch(function(err){
    console.log(err);
});
//以上请求也可以通过这种方式来发送
axios.get('/user',{
            params:{
                ID:12345
               }
    }).then(function(response){
        console.log(response);
    }).catch(function(err){
    console.log(err);
});

2.2:发起post请求示例

post请求的示例:

axios.post('/user',
        {
            firstName:'Fred',
            lastName:'Flintstone'
        }
      ).then(function(res){
        console.log(res);
    }).catch(function(err){
        console.log(err);
});

3:为什么使用async和await

调用axios方法得到的返回值是Promise对象

注意:如果调用某个方法的返回值是Promise实例,则前面可以添加await!

因为await只能用在被async"修饰"方法中,所有使用await需要带async,成对出现

示例:

3.1:结构响应的属性

通过{对象里面的属性名} 解构出想要的属性 

3.2:对结构的属性重命名

通过:的方式对属性进行重命名

4:基于axios.get()和axios.post()发送请求

猜你喜欢

转载自blog.csdn.net/m0_64550837/article/details/134388131
今日推荐