封装 axios 详解

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
fetch()是h5的 axios是第三方的http所以可以用于node.js
本质上还是对原生XMLHttpRequest的封装,可用于浏览器和nodejs的HTTP客户端,只不过它是基于Promise的,符合最新的ES规范


  1. 在浏览器中创建XMLHttpRequest请求
  2. 在node.js中发送http请求
  3. 支持Promise API
  4. 拦截请求和响应
  5. 转换请求和响应数据
  6. 取消要求
  7. 自动转换JSON数据
  8. 客户端支持防止CSRF/XSRF(跨域请求伪造)

需要安装 npm install axios

get支持两种写法

url后面直接添加参数

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

url 后面的参数可以传入一个parmas 对象形式传入

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

post 请求

第二个参数也是直接传入一个对象

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

执行多个并发请求 可以使用promise.all方法解决 

axios方法可以直接调用 里面的method写请求方式 但是传递数据get使用的是params post使用的是data 比较麻烦 不推荐使用这种方法封装

创建实例

//1.允许创建axios实例
const instance = axios.create({
  baseURL: "http://www.pudge.wang:3080/api",
  // 表示超时事件 如果超过这个时间 就不再请求 进行报错
  // Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
  timeout: 1000,
  //请求头
  headers: { "Content-Type": "application/json " },
  //会在原先传的参数的情况下 前面添加一项 可以用于传token
  // get请求使用
  params: {
    token: localStorage.getItem("token"),
  },
  // post请求使用
  data: {
    token: localStorage.getItem("token"),
  },
});

拦截器

请求拦截器

// 2.拦截器
// 请求拦截器
// 在发送请求之前执行这个函数
instance.interceptors.request.use(
  function (config) {
    // 参数config是要发送给后端的所有内容
    // 在发送请求之前统一做一些事情 比如发送token 更换请求头
    // console.log(config);

    // 如果是上传文件的请求 更改请求头
    // if (config.url === "/file/upload") {
    //   config.headers = ...
    // }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

响应拦截器

// 响应拦截器
// 在刚好接收数据的时候执行
instance.interceptors.response.use(
  function (response) {
    console.log(response); //数据对象
    // 对响应数据做点什么
    //?  可以在这里过滤数据 要哪个数据返回哪个数据
    //?  可以在这处理状态码
    if (response.status === 200) {
      return response; //这里return出去的东西是return导get或者post方法的.then方法里
    } else if (response.status === 500) {
      // 抛错导catch
      // 这里404错误无法处理
      throw new Error("505 服务器端错误...");
    }
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

封装大致流程 

import axios from "axios";

//1.允许创建axios实例
const instance = axios.create({
  baseURL: "http://www.xxx/api",
  // 表示超时事件 如果超过这个时间 就不再请求 进行报错
  // Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
  timeout: 1000,
  //请求头
  headers: { "Content-Type": "application/json " },
  //会在原先传的参数的情况下 前面添加一项 可以用于传token
  // get请求使用
  params: {
    token: localStorage.getItem("token"),
  },
  // post请求使用
  data: {
    token: localStorage.getItem("token"),
  },
});

// 2.拦截器
// 请求拦截器
// 在发送请求之前执行这个函数
instance.interceptors.request.use(
  function (config) {
    // 参数config是要发送给后端的所有内容
    // 在发送请求之前统一做一些事情 比如发送token 更换请求头
    // console.log(config);

    // 如果是上传文件的请求 更改请求头
    // if (config.url === "/file/upload") {
    //   config.headers = ...
    // }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器
// 在刚好接收数据的时候执行
instance.interceptors.response.use(
  function (response) {
    console.log(response); //数据对象
    // 对响应数据做点什么
    //?  可以在这里过滤数据 要哪个数据返回哪个数据
    //?  可以在这处理状态码
    if (response.status === 200) {
      return response; //这里return出去的东西是return导get或者post方法的.then方法里
    } else if (response.status === 500) {
      // 抛错导catch
      // 这里404错误无法处理
      throw new Error("505 服务器端错误...");
    }
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

const http = {
  // 参数可以直接传递 params直接是对象
  get(url, params) {
    //使用实例请求 可以直接自动拼接baseURL
    return instance
      .get(url, {
        params: params,
      })
      .then((res) => {
        if (res.data.status === 0) {
          return res;
        }
      })
      .catch((err) => {
        //   捕获错误信息 timeout of 1000ms exceeded  捕获之后可以将这个换成轻提示
        // console.log(err.message);
        if (err.message === "timeout of 1000ms exceeded") {
          alert("请求超时");
        }
        alert("服务器端错误");
      });
  },
  post(url, data) {
    return instance
      .post(url, data)
      .then((response) => {
        return response;
      })
      .catch((error) => {
        console.log(error);
      });
  },
};

export default http;

不同地址api封装

import http from "./http";

export const ratedApi = (params) => http.get("/rated/list", params);//将对应的地址封装 params参数是传递的数据

页面引入api封装地址 直接调用对应函数使用 参数可以进行传递

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值