Axios库使用

Axios库使用

2026年5月15日·#前端基础前端/Ajax·393 字 2 分钟
浏览量加载中...
AI 摘要

基于Promise的Axios HTTP客户端发送GET/POST请求及与async/await配合使用

Axios库使用#

定义#

Axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js环境。它对原生的Ajax进行了封装,简化了HTTP请求的编写和响应处理。

语法/用法#

官方文档#

Axios官网:https://www.axios-http.cn

引入Axios#

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

通用方式发送请求#

// GET请求
axios({
url: 'https://api.example.com/data',
method: 'get'
}).then(function(res) {
console.log(res.data);
}).catch(function(err) {
console.log(err);
})
// POST请求
axios({
url: 'https://api.example.com/update',
method: 'post'
}).then(function(res) {
console.log(res.data);
}).catch(function(err) {
console.log(err);
})

请求方法别名#

// GET请求
axios.get("https://api.example.com/data")
.then(result => {
console.log(result.data);
})
// POST请求
axios.post("https://api.example.com/update", "id=1")
.then(result => {
console.log(result.data);
})
// 带参数GET请求
axios.get(`https://api.example.com/list?name=${name}&gender=${gender}&job=${job}`)
.then(res => {
this.empList = res.data.data;
})

与async/await结合使用#

async search() {
const result = await axios.get(
`https://api.example.com/list?name=${this.searchForm.name}`
);
this.empList = result.data.data;
}

常见场景#

  1. GET请求:获取数据、查询操作
  2. POST请求:提交表单、创建数据
  3. PUT请求:更新数据
  4. DELETE请求:删除数据
  5. 并发请求:同时发送多个请求并处理

注意事项#

  1. 引入方式

    • 可以通过CDN引入(在线)
    • 可以通过npm安装(本地)
    • 建议使用离线版本以提高稳定性
  2. 响应处理

    • 响应数据在res.data
    • 使用.then()处理成功响应
    • 使用.catch()处理错误响应
  3. 请求方法区别

    • GET请求参数在URL中
    • POST请求参数在请求体中
  4. async/await优化

    • 使用async/await可以让异步代码像同步代码一样编写
    • 提高代码可读性和可维护性
    • 建议在前端项目中优先使用此方式
  5. 常见错误处理

    • 网络错误
    • 服务器返回错误状态码
    • 超时问题
    • 跨域问题
最后更新于 2026-05-15,距今已过 94 天

部分内容可能已过时

评论区

[ 标签 ]
# AI5# AI 编程2# AI工具1# Ajax2# Apifox1# AstrBot2# Astro2# CC Switch1# CDN2# Claude Code1# claudecode2# ClaudeCode1# CloudFlare2# Cloudflare1# CloudFlare-ImgBed1# coc3# CSS6# DeepSeek2# deepseek2# DELETE1# Docker1# EdgeOne3# Gist1# git1# GitHub1# hexo-circle-of-friends1# HTML6# HTTP2# Java23# java13# JavaScript5# JDBC3# JSON1# JUnit1# Logback1# Maven6# Mybatis1# MyBatis4# MySQL6# MySql1# NapCat1# Obsidian3# OpenCode3# ORM1# PathVariable1# PicGo1# py2# RequestBody1# RequestMapping1# RESTful风格1# skills1# Slf4j1# SpringBoot11# SQL2# Svelte2# TailwindCSS1# Telegram2# Tlias2# Vercel1# Vue7# Waline3# WebDAV1# Web基础6# WinSCP1# YAML1# 三层架构1# 中二宣言1# 书籍1# 使用文档9# 写作1# 刷步数1# 前端32# 动态1# 动漫1# 单词2# 博客6# 博客工作流1# 博客开发2# 参数接收1# 友链1# 反思2# 图床4# 地图1# 备份1# 奇思妙想1# 存储1# 学习方法1# 宝塔面板3# 宝宝9# 导航栏1# 工具2# 开发1# 开发规范1# 开心1# 影视1# 微信1# 性能优化2# 总结1# 想法7# 感悟9# 指南1# 插件3# 故障排除1# 效率工具2# 教程7# 数据库10# 斩神1# 日常60# 日志框架1# 朋友圈1# 朱元璋1# 模板1# 测试1# 游戏1# 生活迁移1# 电影2# 碎碎念1# 视觉识别1# 网络教室1# 羊毛1# 脚本1# 脚本工具1# 自动化2# 蓝奏云1# 订阅推荐1# 记录1# 评论系统1# 词根1# 词缀1# 说说1# 足迹1# 跑步2# 路径参数1# 转载1# 运动1# 部落冲突1# 配置1# 随机图1# 音乐3# 音标1# 饮食1# 驼峰命名1# 高德地图1
[ 公告 ]

如果你喜欢,那么欢迎来到我的世界!

了解更多
[ 音乐 ]
封面

音乐

暂未播放

0:000:00
暂无歌词
找不到相关结果。
[ contents ]
[ 全部文章 ]
工具