axios的基本使用

3 篇文章 0 订阅
1 使用json-server创建一个假的rest api服务
1 安装 npm install -g json-server 
2 创建一个json文件
3 启动服务 json-server --watch db.json
2 axios 的特点
1 Make XMLHttpRequests from the browser  在浏览器端发送Ajax请求
2 Make http requests from node.js  在node.js中发送http请求
3 Supports the Promise API  支持promise的相关操作
4 Intercept request and response  **请求响应拦截器 非常重要**
5 Transform request and response data 对请求和响应数据做转换
6 Cancel requests 取消请求
7 Automatic transforms for JSON data  自动将结果准换为json数据 
8 Client side support for protecting against XSRF 做保护 阻挡一些跨站攻击
3 安装axios
```
---Using npm:
$ npm install axios

---Using bower:
$ bower install axios

---Using cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
```
4 常用的属性
1 //请求类型
method: 'POST',
2 //URL
url: 'http://localhost:3000/posts',
3 //设置请求体
data: {
    title: "今天天气不错, 还挺风和日丽的",
    author: "张三"
}
5 发送请求的常用方法
1 axios 函数
    ```
    btns[0].onclick = function(){
        //发送 AJAX 请求
        axios({
            //请求类型
            method: 'GET',
            //URL
            url: 'http://localhost:3000/posts/2',
        }).then(response => {
            console.log(response);
        });
    }

    ```

2 request
    ```
    btns[0].onclick = function(){
        // axios()
        axios.request({
            method:'GET',
            url: 'http://localhost:3000/comments'
        }).then(response => {
            console.log(response);
        })
    }
    ```
3 post
    ```
    btns[0].onclick = function(){
        // 参数  url data请求体 config配置对象 2 3可选
        axios.post(
            'http://localhost:3000/comments', 
            {
                "body": "test",
                "postId": 2
            }).then(response => {
                console.log(response);
            })
    }
    ```
6 axios响应结果
1 config 配置对象
2 data 响应体 服务器返回的结果
3 headers 响应头信息
4 request 原生的ajax请求对象
5 status 响应状态码
6 statusText 响应状态字符串
7 axios 请求常用配置对象
url      // 请求路径
method   // 请求方法  默认get
baseURL  //设定url的基础结构
transformRequest  //预处理 
transformResponse
headers  // 头信息
params   // 请求参数
proxy  // 代理
8 axios默认配置 简化代码
```
    axios.defaults.method = 'GET';//设置默认的请求类型为 GET
    axios.defaults.baseURL = 'http://localhost:3000';//设置基础 URL
    axios.defaults.params = {id:100};
    axios.defaults.timeout = 5000;// 请求超时时间

    btns[0].onclick = function(){
        axios({
            url: '/posts'
        }).then(res => {
            // 拿到结果
            console.log(res.data);
        })
    }
```
9 axios创建实例对象 发送请求
```
    const test1 = axios.create({
        baseURL: 'https://a.com',
        timeout: 2000
    });

    const test2 = axios.create({
        baseURL: 'https://b.com',
        timeout: 2000
    });
```
10 axios 拦截器
1 什么是拦截器
 就是一些函数 分为两类,请求拦截器和响应拦截器

2 请求拦截器
  在发送请求之前 借助一些函数 来对请求参数和内容做处理检测 如果都没有问题再去发送请求  如果有问题则取消发送
    ```
        // config 配置对象
        axios.interceptors.request.use(function (config) {
            console.log('请求拦截器 成功');
            if(config.params === ''){
                throw '参数不能为空!!!'
            }else{
                config.params = {a:100};
                return config;
            }
        }, function (error) {
            console.log('请求拦截器 失败');
            return Promise.reject(error);
        });
    ```

3 响应拦截器
    当服务器返回结果之前 先对结果做一些预处理
    ```
        // response 响应结果
        axios.interceptors.response.use(function (response) {
            console.log('响应拦截器 成功');
            return response.data;
            // return response;
        }, function (error) {
            console.log('响应拦截器 失败')
            return Promise.reject(error);
        });
    ```
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值