Axios学习笔记

Axios简介

axios前端异步请求库类似JQuery ajax技术,
ajax用来在页面发起异步请求到后端服务,并将后端服务响应数据渲染到页面上,
jquery推荐ajax技术,但vue里面并不推荐在使用jquery框架,vue推荐使用axios异步请求库。
axios总结:

  • 用来在前端页面发起一个异步请求,请求之后页面不动,响应回来刷新页面局部;
  • 官方定义: axios 异步请求库并不是vue官方库第三方异步库在vue中推荐axios;
  • 特点:易用、简洁且高效的http库 ---> 发送http异步请求库。

Axios功能&特性

  • 从浏览器中创建XLHttpRequests从 node.js 创建http请求(发送axios异步请求)
  • 支持Promise API
  • 拦截请求和响应(做拦截器)
  • 转换请求数据和响应数据取消请求
  • 自动转换JSON数据,客户端支持防御XSRF

常规使用

发送Get请求,查询:

复制代码
axios.get("http://localhost:8081/demo?id=21&name=xiaowang ").then( function(res){
    //代表请求成功之后处理
    console.1og (res.data);
}).catch( function (err){
    //代表请求失败之后处理
    alert ('进入catch ')
    console.log (err);
});

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345').then(function (response) {
    console.log(response);
  }).catch(function (error) {
    console.log(error);
  });

// 可选的,上面的请求可以这样做
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);
  });

其他请求

复制代码
axios.put(.then( ).catch ( ); //修改
axios.patch( ).then( ).catch( );
axios.delete( "ur1?id=21").then ( ).catch ( ); //删除

Axios的封装

复制代码
import axios from 'axios'
export default function axios(option){
    return new Promise((resolve,reject) => {
    //1.创建sxios实例
    const instance = axios.create({
        url: 'api',
        timeout: 5000,
        headers: ''
    })
    //2.传入对象进行网络请求
    instance(option).then(res => {
        resolve(res)
    }).catch(err => {
        reject(err)
    })
})
}

Axios创建默认实例发送请求

复制代码
//创建axios的配置对象
var instance = axios. create({
    baseURL: 'http://localhost:8081/',        //基础路径,后面的请求的url就直接写接口路径就行
    timeout: 5000,
});

这里的请求地址,直接写对应的接口路径
instance.get("/demo?id=21&name=xiaowang ").then( function(res) {
    //代表请求成功之后处理
    console.log(res);
    console.1og (res.data);
}).catch( function (err) {
    //代表请求失败之后处理
    alert ('进入catch ');
    console.log (err);
});

Axios封装一个request请求

复制代码
export function request(config, success, failure) {
  // 1.创建axios的实例
  const instance = axios.create({
    baseURL: 'http://127.0.0.1:8080',
    timeout: 5000
  })
  // 发送真正的网络请求
  instance(config).then(res => {
      success(res);
    }).catch(err => {
      failure(err)
    })
}

Axios拦截器

请求拦截器

请求拦截器作用是在发出请求时,拦截下用户的请求,执行完一系列处理再发送出去(像添加cookie、token,请求头等)

配置请求拦截器

  • 首先创建一个axios实例对象

    import axios from 'axios'
    import { ELMessage } from 'element-plus'
    const myRequest = axios.create({
    baseURL: process.env.BASE_API, // 这里可以写自己访问的地址,例如127.0.0.1
    timeout: 3000, // 请求超时时间
    headers: {
    "Content-Type": "application/json;charset=utf-8"
    }
    })

  • 接下来就是配置请求拦截器(interceptor.request)

    myRequest.interceptors.request.use(
    req=>{...}, // 对发起的请求进行处理,方法写在{}中,req是请求参数
    err=>{...}, // 出现请求错误时进行的处理
    }

下面写一个设置token的实例:

复制代码
myRequest.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token') // 获取存取的token
        if(token){ // 不为空的话就设置进headers
            config.headers['token'] = token
        }
        return config
    },
    err => {
        return Promise.reject(error)
    }
)

响应拦截器

配置响应拦截器

复制代码
myRequest.interceptors.response.use(
        res=>{...}, // 对响应进行处理,方法写在{}中,res是返回数据
        err=>{...}, // 出现请求错误时进行的处理
)

假如服务器的响应为:

复制代码
{
        "errCode" : 0,
        "errDesc" : "Success",
        "data": "xxxxxx"
}

这时候我们可以这样写响应拦截器:

复制代码
myRequest.interceptors.response.use(
    res => {
        if(res.errCode ==  0){
            return Promise.resolve(res.data)
           }
        else {
            ElMessage({
                message: "Error",
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(new Error("Error Message"))
        }
    },
    err => {
        ElMessage({
            message: err.data.message,
            type: 'error',
            duration: 5 * 1000
        })
    }
)

通过上面的处理之后,我们axios.xxx().then((res)=>{...})的res就为响应数据的data,其中errCode和errDesc就被处理掉了。

相关推荐
Allen_LVyingbo26 分钟前
数智读书笔记系列035《未来医疗:医疗4.0引领第四次医疗产业变革》
人工智能·经验分享·笔记·健康医疗
岑梓铭34 分钟前
考研408《计算机组成原理》复习笔记,第三章(3)——多模块存储器
笔记·考研·408·计算机组成原理
菜菜why1 小时前
MSPM0G3507学习笔记(一) 重置版:适配逐飞库的ti板环境配置
笔记·学习·电赛·嵌入式软件·mspm0
夜阑卧听风吹雨,铁马冰河入梦来1 小时前
Spring AI 阿里巴巴学习
人工智能·学习·spring
c7691 小时前
【文献笔记】Automatic Chain of Thought Prompting in Large Language Models
人工智能·笔记·语言模型·论文笔记
板栗焖小鸡2 小时前
STM32-PWM驱动无源蜂鸣器
stm32·学习
X_StarX2 小时前
【Unity笔记01】基于单例模式的简单UI框架
笔记·ui·unity·单例模式·游戏引擎·游戏开发·大学生
Code季风2 小时前
Gin 中间件详解与实践
学习·中间件·golang·go·gin
智者知已应修善业4 小时前
【51单片机用数码管显示流水灯的种类是按钮控制数码管加一和流水灯】2022-6-14
c语言·经验分享·笔记·单片机·嵌入式硬件·51单片机
孞㐑¥7 小时前
Linux之Socket 编程 UDP
linux·服务器·c++·经验分享·笔记·网络协议·udp