axios模块封装及常见的配置选项

axios模块封装

  • 创建一个network文件夹
    • 创建一个request.js文件
    • 创建一个main.js文件

request.js

import axios from 'axios'

export function request(config) {
    //1.创建axios的实例
    const instance = axios.create({
        timeout: 5000//超时设置
    })

    //2.axios拦截器
    //2.1请求拦截的作用
    axios.interceptors.request.use(config => {
        console.log(config)
        //1.比如说config中的一些信息不符合服务器的要求
        //2.比如每次发送网络请求时,都希望在界面中显示一个请求的图标
        //3.某些网络请求(比如登陆(token)),必须携带一些特殊的信息
        return config
    }, err => {
        console.log(err)
    })

    //2.2 响应拦截的作用
    axios.interceptors.response.use(res => {
        console.log(res)
    }, err => {
        console.log(err)
    })

    //3.发送真正的网络请求
    return instance(config)
}

main.js

import {request} from './request'

export function 函数名(){
    return request({
        url: '请求地址'
    })
}

使用

函数名()
        .then(res => {
           console.log(res)
        })
        .catch(

        );

常见的配置选项

  • 请求地址

    • url: '/user'
  • 请求类型,默认get

    • methods: 'get'
  • 请求根路径

    • baseURL: 'http://www.aaa.com/api'
  • 请求前的数据处理

    • transformRequest: [function(data) {}]
  • 自定义的请求头

    • headers: {'x-Requested-With': 'XMLHttpRequest'}
  • URL查询对象(get请求)

    • params: {name: lazy}
  • 查询对象序列化函数

    • paramsSerializer: function(params){}
  • request body(post请求)

    • data: {name: lazy}
  • 超时设置(s)

    • timeout: 1000
  • 跨域是否带Token

    • withCredentials: false
  • 自定义请求处理

    • adapter: function(resolve, reject, config){}
  • 身份验证信息

    • auth: {uname: '', pwd: '12'}
  • 响应的数据格式

    • responseType: 'json'
posted @   懒惰ing  阅读(380)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示