当前位置: 首页 > news >正文

axios请求

安装 Axios

在项目中安装 Axios 依赖,可以通过 npm 或 yarn 进行安装。

npm install axios

yarn add axios

引入 Axios

在需要使用 Axios 的文件中引入 Axios。

import axios from 'axios';

发起 GET 请求

使用 Axios 发起 GET 请求,获取数据。

axios.get('https://api.example.com/data').then(response => {console.log(response.data);}).catch(error => {console.error(error);});

发起 POST 请求

使用 Axios 发起 POST 请求,发送数据到服务器。

axios.post('https://api.example.com/data', { key: 'value' }).then(response => {console.log(response.data);}).catch(error => {console.error(error);});

配置全局默认值

设置 Axios 的全局默认配置,例如 baseURL 和 headers。

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';

创建 Axios 实例

创建自定义的 Axios 实例,用于不同的 API 配置。

const api = axios.create({baseURL: 'https://api.example.com',timeout: 1000,headers: { 'X-Custom-Header': 'foobar' }
});api.get('/data').then(response => {console.log(response.data);});

处理请求和响应拦截器

使用拦截器在请求或响应被处理前进行统一处理。

axios.interceptors.request.use(config => {config.headers.Authorization = 'Bearer token';return config;
}, error => {return Promise.reject(error);
});axios.interceptors.response.use(response => {return response.data;
}, error => {return Promise.reject(error);
});

取消请求

使用 CancelToken 取消正在进行的请求。

const CancelToken = axios.CancelToken;
const source = CancelToken.source();axios.get('https://api.example.com/data', {cancelToken: source.token
}).catch(error => {if (axios.isCancel(error)) {console.log('Request canceled', error.message);}
});source.cancel('Operation canceled by the user.');

并发请求

使用 axios.allaxios.spread 处理并发请求。

axios.all([axios.get('https://api.example.com/data1'),axios.get('https://api.example.com/data2')
]).then(axios.spread((response1, response2) => {console.log(response1.data, response2.data);
}));

错误处理

统一处理请求中的错误,包括网络错误和服务器错误。

axios.get('https://api.example.com/data').then(response => {console.log(response.data);}).catch(error => {if (error.response) {console.error(error.response.status, error.response.data);} else if (error.request) {console.error(error.request);} else {console.error(error.message);}});

http://www.dtcms.com/a/473649.html

相关文章:

  • 109、23种设计模式之迭代器模式(18/23)
  • 餐饮设计公司网站wordpress如何保存
  • 前端页面出现问题ResizeObserver loop completed with undelivered notifications.
  • 有声阅读网站如何建设邵阳学院研究生与学科建设处网站
  • AWS RDS Aurora MySQL高CPU使用率问题诊断与解决实战
  • 【Swift】LeetCode 11. 盛最多水的容器
  • 设计模式之 享元模式 Flyweight
  • 智械觉醒当AI开始思考“我是谁”
  • 商河 网站建设公司网站的具体的建设方案
  • 湖南省网站备案婚纱摄影网站应该如何做优化
  • pytest学习
  • seo网站建设厦门百度广告代理商查询
  • 【全连接神经网络】基本原理
  • Go 异步编程
  • 基于贪心最小化包围盒策略的布阵算法
  • 《Python 异步数据库访问全景解析:从阻塞陷阱到高性能实践》
  • AI 自己造“乐高积木”:生成式 AI 设计可拼装模块化硬件的实战笔记
  • 10.11笔记
  • 冒泡排序的多种实现方式详解
  • 网页设计平面设计温州网站优化页面
  • 特别分享:聊聊Git
  • M|蝙蝠侠:侠影之谜
  • crawl4ai智能爬虫(一):playwright爬虫框架详解
  • 探究Java、C语言、Python、PHP、C#与C++在多线程编程中的核心差异与应用场景
  • 国外网站模板网站建设ui培训班好
  • 瑞安建设公司网站旅游网站系统的设计与实现
  • MongoDB-基本介绍(一)基本概念、特点、适用场景、技术选型
  • 国产之光金仓数据库,真能平替MongoDB?实测来了!
  • 网站开发需要学什么语言wordpress所有栏目循环输出
  • 低代码革命:拖拽式界面生成器与API网关的深度集成