Axios

67 阅读1分钟

一、json-server的介绍与服务搭建

1. 安装

npm install -g json-server

2. 创建文件

db.json文件内容

{
    "posts":[
        {
            "id":1,
            "title":"json-server",
            "author":"typicode"
        }
    ],
    "comments":[
        {
            "id":1,
            "body":"some comment",
            "postId":1
        }
    ],
    "profile":{
        "name":"typicode"
    }
}

3. 启动服务

 json-server --watch db.json

image.png

点击url可以查看到所有的数据

二、axios

1.介绍

image.png

2.下载

image.png

3.基本使用

image.png

  1. GET

image.png

image.png

image.png

  1. POST

image.png

image.png

  1. PUT

image.png

image.png

  1. DELETE

image.png

image.png

4.axios其他方式发送请求

image.png

5. axios请求响应结果的结构

image.png

6. axios默认配置

避免后续反复配置

image.png

7. axios创建实例对象发送请求

axios.create()

image.png

image.png

优势:

  • 给多个服务器发送请求的时候方便,因为axios.defaults只能设置一个基础默认url

8.axios拦截器(重要)

  1. 拦截器:本质是函数

  2. 拦截器分为两类:

    • 请求拦截器:在发送请求之前可以借助一些函数对请求的参数、内容进行一些检测
    • 响应拦截器:对响应的结果进行预处理
// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

执行顺序:

image.png

image.png

9.axios取消请求

  1. 添加配置对象的属性
  2. 声明全局变量
  3. 将c的值赋值给cancel
  4. 取消请求

image.png

在发送请求前先取消上一个请求(防止用户抢单等连续点击,导致服务器压力过大)

image.png