首页 > 其他分享 >axios 使用

axios 使用

时间:2024-02-06 14:26:46浏览次数:23  
标签:function axios 使用 request error config response

官网

https://axios-http.com/

安装

npm install axios

使用格式

axios.method({configs})
.then(function(response){
    //
})
.catch(function (error) {
    // handle error
    console.log(error);
})
.finally(function () {
    // always executed
});

axios函数

axios(config)
axios(url[, config])

实例:

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

别名请求方法

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
axios.postForm(url[, data[, config]])
axios.putForm(url[, data[, config]])
axios.patchForm(url[, data[, config]])

config 支持的参数:https://axios-http.com/docs/req_config

HTTP GET

axios.get('/user?ID=12345', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

HTTP POST

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

HTTP POST multipart

const {data} = await axios.post('https://httpbin.org/post', {
    firstName: 'Fred',
    lastName: 'Flintstone',
    orders: [1, 2, 3],
    photo: document.querySelector('#fileInput').files
  }, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }
)

支持的请求参数

config 支持的参数:https://axios-http.com/docs/req_config

优先级:请求配置 > 实例配置 > 全局配置

返回的数据格式(Response Schema)

https://axios-http.com/docs/res_schema

默认配置(Config Defaults)

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

处理错误(Handling Errors)

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

拦截器(Interceptors)

官方文档:https://axios-http.com/docs/interceptors
请求拦截器

// 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);
  });

取消请求

官方文档:https://axios-http.com/docs/cancellation

取消单个请求

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

取消多个请求

const CancelToken = axios.CancelToken;
let cancel1;
let cancel2;

axios.get('/abc.pdf', {
    timeout:50000,
    cancelToken: new CancelToken(function executor(c) {
        // An executor function receives a cancel function as a parameter
        cancel1 = c;
    })
});

axios.get('/abc.pdf', {
    timeout:50000,
    cancelToken: new CancelToken(function executor(c) {
        // An executor function receives a cancel function as a parameter
        cancel2 = c;
    })
});

// cancel the request
cancel1();
cancel2();

Async

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

等待任务全部完成

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

const [acct, perm] = await Promise.all([getUserAccount(), getUserPermissions()]);

// 或者

Promise.all([getUserAccount(), getUserPermissions()])
  .then(function ([acct, perm]) {
    // ...
  });

标签:function,axios,使用,request,error,config,response
From: https://www.cnblogs.com/cqpanda/p/17306297.html

相关文章

  • 【OpenVINO™】在 MacOS 上使用 OpenVINO™ C# API 部署 Yolov5
    在MacOS上使用OpenVINO™C#API部署Yolov5项目介绍YOLOv5是革命性的"单阶段"对象检测模型的第五次迭代,旨在实时提供高速、高精度的结果,是世界上最受欢迎的视觉人工智能模型,代表了Ultralytics对未来视觉人工智能方法的开源研究,融合了数千小时研发中......
  • 弹窗组件一般需要使用memo记忆化吗
    弹窗组件(Modal)是否需要使用记忆化(memoization),主要取决于该组件的性能优化需求以及其内部复杂性。记忆化是一种用于优化函数或组件性能的技术,它通过缓存先前计算的结果以避免在相同的输入参数下重复执行耗时的操作。对于一个简单的弹窗组件而言,如果其内容不涉及复杂的计算或者大量......
  • 使用无代码/低代码平台进行开发的 5 大挑战
    近年来,越来越多的开发者会选择使用无代码/低代码平台进行业务系统的开发。原因很简单:不用从零开始研发一整套系统,并且有易用的模版和可视化的操作界面,大大减少了业务开发的难度和所需时间。然而,真正尝试过的开发者会发现,无代码/低代码确实能让开发变“简单”,但新的挑战也随之而来。......
  • 1 使用venv创建Python虚拟环境
    Python从3.3版本开始,自带虚拟环境配置包venv。虚拟环境下通过pip命令下载的Python包不会影响到系统中的Python,可以做到项目之间环境的分离(目前Pycharm新建环境默认使用这种方式)。创建环境py-mvenvenviron上述命令创建虚拟环境environ。激活环境首先进入Scripts文件夹:cde......
  • 使用JS来开发ProComponents的ProTable案例
    ProComponents的ProTable组件是基于React和TypeScript开发的,但也可以在JavaScript项目中使用。以下是一个使用JavaScript的ProTable示例:import{useState,useRef}from'react';import{Button}from'antd';importProTablefrom'@ant-design/pro-table&#......
  • git命令的基本使用
    目录一、概念二、git命令1、git初始配置全局的用户名、邮箱和密码2、git本地仓库常用操作3、git远程仓库常用操作4、git分支常用操作5、其他命令或操作三、注意事项1、gitpush命令出现403错误2、用SSH方式下载/克隆远程仓库3、.gitignore文件一、概念Git是一个用于管理源代码的......
  • Iron Python中使用NLTK库
    因为我是程序员,所以会写各种语言的爬虫模版,对于使用NLTK库也是有很的经验值得大家参考的。其实总的来说,NLTK是一个功能强大的NLP工具包,为研究人员和开发者提供了丰富的功能和资源,用于处理和分析文本数据。使用非常方便,而且通俗易懂,今天我将例举一些问题以供大家参考。1、问题背景......
  • 使用文心一言编写小红书带货文案
    Q:小红书苹果手机壳带货文案:有个性、有颜值、适合年轻人A:......
  • Windows下如何使用 Sublime Text 4 配置 C/C++ 环境(使用LSP-clangd)
    1软件安装1.1SublimeText4安装及PackageControl安装略,请自行百度/必应/谷歌。1.2Clang环境安装1.2.1Clang下载在LLVMMinGW下载最新版Clang编译器,此处应根据个人电脑系统及版本选择,本文选择llvm-mingw-20231128-ucrt-x86_64.zip,后续文件名将以此为例。各版本......
  • 家用电脑装esxi使用尝试和解决no network Adapters和VMware PowerCLI安装
    因为电脑换了新配置,老的电脑目前就没在用,想着闲置再利用一下的原则,想给他安装一下esxi,正好也可以折腾一下系统。我的主板是技嘉B85M-HD3-A的,查一下 VMwareCompatibilityGuide-I/ODeviceSearch 这个选择对应网卡型号,就能看到他支持的版本。很可惜,我的这个主板上带的这个网......