axios基础入门教程

一、axios 简介

axios 是一个基于 Promise 的 HTTP 客户端,可用于浏览器和 Node.js 环境,支持以下特性:

发送 HTTP 请求(GET/POST/PUT/DELETE 等)

拦截请求和响应

自动转换 JSON 数据

取消请求

并发请求处理

二、安装

1. 使用 npm/yarn

npm install axios# 或yarn add axios

2. 浏览器直接引入

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

三、基本用法

1. 发送 GET 请求

axios.get('https://api.example.com/data')  .then(response => {    console.log(response.data); // 响应数据  })  .catch(error => {    console.error('请求失败:', error);  });

2. 发送 POST 请求​​​​​​​

axios.post('https://api.example.com/data', {    name: 'John',    age: 30  })  .then(response => {    console.log(response.data);  });

3. 使用 async/await​​​​​​​

async function fetchData() {  try {    const response = await axios.get('https://api.example.com/data');    console.log(response.data);  } catch (error) {    console.error(error);  }}

四、请求配置

1. 全局默认配置​​​​​​​

axios.defaults.baseURL = 'https://api.example.com';axios.defaults.headers.common['Authorization'] = 'Bearer token123';axios.defaults.timeout = 5000; // 超时时间

2. 单个请求配置​​​​​​​

axios.get('/data', {  params: { id: 1 }, // 查询参数  headers: { 'X-Custom-Header': 'value' }});

五、响应结构

响应对象包含以下字段:​​​​​​​

{  data: {},       // 服务器返回的数据  status: 200,    // HTTP 状态码  statusText: 'OK',  headers: {},     // 响应头  config: {},      // 请求配置  request: {}      // 原始的 XMLHttpRequest 对象(浏览器)}

六、错误处理

1. 通用错误捕获​​​​​​​

axios.get('/data')  .catch(error => {    if (error.response) {      // 服务器返回了非 2xx 状态码      console.log(error.response.status);      console.log(error.response.data);    } else if (error.request) {      // 请求已发送但无响应      console.log('No response received');    } else {      // 请求配置错误      console.log('Error:', error.message);    }  });

2. 全局错误拦截​​​​​​​

axios.interceptors.response.use(  response => response,  error => {    // 统一处理错误    return Promise.reject(error);  });

七、高级功能

1. 并发请求​​​​​​​

const request1 = axios.get('/data1');const request2 = axios.get('/data2');axios.all([request1, request2])  .then(axios.spread((res1, res2) => {    console.log(res1.data, res2.data);  }));

2. 取消请求​​​​​​​

const source = axios.CancelToken.source();axios.get('/data', {  cancelToken: source.token}).catch(thrown => {  if (axios.isCancel(thrown)) {    console.log('请求被取消:', thrown.message);  }});// 取消请求source.cancel('用户取消操作');

3. 请求拦截器​​​​​​​

axios.interceptors.request.use(  config => {    // 在发送请求前做些什么(如添加 token)    config.headers.Authorization = 'Bearer token';    return config;  },  error => {    return Promise.reject(error);  });

八、常见场景示例

1. 上传文件​​​​​​​

const formData = new FormData();formData.append('file', fileInput.files[0]);axios.post('/upload', formData, {  headers: { 'Content-Type': 'multipart/form-data' }});

2. 下载文件​​​​​​​

axios.get('/download', { responseType: 'blob' })  .then(response => {    const url = window.URL.createObjectURL(new Blob([response.data]));    const link = document.createElement('a');    link.href = url;    link.setAttribute('download', 'file.pdf');    document.body.appendChild(link);    link.click();  });

九、最佳实践

封装 axios:创建 api.js 统一管理接口

环境区分:通过 .env 文件配置不同环境的 baseURL

安全防护:结合 CSRF Token 或 JWT 进行身份验证

性能优化:合理设置超时时间,使用缓存策略

示例:

以下是使用 Axios 和 Spring Boot 实现前后端分离的登录功能的步骤详解:

1. 后端实现(Spring Boot)

1.1 添加依赖

在 pom.xml 中添加必要依赖:​​​​​​​

<!-- Spring Web --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency><!-- 数据库(以 JPA + H2 为例) --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency>    <groupId>com.h2database</groupId>    <artifactId>h2</artifactId>    <scope>runtime</scope></dependency><!-- 密码加密 --><dependency>    <groupId>org.springframework.security</groupId>    <artifactId>spring-security-crypto</artifactId></dependency>

1.2 配置数据库和加密

在 application.properties 中配置:​​​​​​​

spring.datasource.url=jdbc:h2:mem:testdbspring.datasource.driverClassName=org.h2.Driverspring.h2.console.enabled=truespring.jpa.hibernate.ddl-auto=update

1.3 创建用户实体类​​​​​​​

@Entitypublic class User {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    @Column(unique = true)    private String username;    private String password;    // Getters and Setters}

1.4 创建 Repository​​​​​​​

public interface UserRepository extends JpaRepository<User, Long> {    User findByUsername(String username);}

1.5 创建 Service 层​​​​​​​

@Servicepublic class AuthService {    @Autowired    private UserRepository userRepository;    @Autowired    private BCryptPasswordEncoder passwordEncoder;    public boolean authenticate(String username, String password) {        User user = userRepository.findByUsername(username);        return user != null && passwordEncoder.matches(password, user.getPassword());    }}

1.6 创建 Controller​​​​​​​

@RestController@RequestMapping("/api/auth")@CrossOrigin(origins = "http://localhost:3000") // 允许前端跨域请求public class AuthController {    @Autowired    private AuthService authService;    @PostMapping("/login")    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {        boolean isValid = authService.authenticate(            loginRequest.getUsername(),            loginRequest.getPassword()        );        if (isValid) {            return ResponseEntity.ok().body("登录成功");        } else {            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");        }    }}// 登录请求DTOpublic class LoginRequest {    private String username;    private String password;    // Getters and Setters}

2. 前端实现(使用 Axios)

2.1 安装 Axios

npm install axios

2.2 登录组件示例(React)​​​​​​​

import React, { useState } from 'react';import axios from 'axios';const LoginForm = () => {    const [username, setUsername] = useState('');    const [password, setPassword] = useState('');    const [error, setError] = useState('');    const handleSubmit = async (e) => {        e.preventDefault();        try {            const response = await axios.post(                'http://localhost:8080/api/auth/login',                { username, password },                { headers: { 'Content-Type': 'application/json' } }            );            if (response.status === 200) {                alert('登录成功');                // 跳转到主页或处理登录状态            }        } catch (err) {            if (err.response && err.response.status === 401) {                setError('用户名或密码错误');            } else {                setError('登录失败,请重试');            }        }    };    return (        <form onSubmit={handleSubmit}>            <input                type="text"                value={username}                onChange={(e) => setUsername(e.target.value)}                placeholder="用户名"            />            <input                type="password"                value={password}                onChange={(e) => setPassword(e.target.value)}                placeholder="密码"            />            {error && <div className="error">{error}</div>}            <button type="submit">登录</button>        </form>    );};export default LoginForm;

3. 测试流程

启动 Spring Boot 应用:

mvn spring-boot:run

启动前端应用:

npm start

在登录页面输入用户名和密码,验证是否返回正确响应。

 

 

 

 

 

### 如何在 DevEco Studio 中安装和使用 Axios #### 1. 环境准备 确保使用的 DevEco Studio 和 SDK 版本满足最低需求。已知在以下环境中验证通过:DevEco Studio: 4.1 Canary2(4.1.3.325),SDK: API11(4.1.0.36)[^1]。 #### 2. 安装 Axios 库 为了引入 Axios 到 HarmonyOS 或 OpenHarmony 的项目中,需执行如下操作: - 打开项目的 `package.json` 文件,在依赖项部分添加 Axios 支持库: ```json { "dependencies": { "@ohos/axios": "^latest" } } ``` 保存文件后,运行命令以更新依赖环境: ```bash npm install ``` 此过程会自动下载并配置 Axios 及其相关模块到当前项目目录下[^2]。 #### 3. 使用 Axios 进行网络请求 以下是基于 Axios 实现 HTTP 请求的一个简单示例代码片段: ```typescript // 导入必要的模块 import axios, { AxiosInstance, AxiosRequestConfig } from '@ohos/axios'; import { LogUtils } from '../utils/LogUtils'; const instance: AxiosInstance = axios.create({ baseURL: 'https://api.example.com', // 替换为目标服务器地址 timeout: 10000, }); function fetchData(): void { const config: AxiosRequestConfig = { method: 'get', url: '/data' }; instance(config).then((response) => { console.log(response.data); LogUtils.info('Data fetched successfully'); }).catch((error) => { console.error(error); LogUtils.error('Error occurred while fetching data'); }); } fetchData(); ``` 上述代码展示了如何创建一个 Axios 实例,并设置基本 URL 和超时时间参数。随后定义了一个函数用于发起 GET 请求获取数据。 #### 4. 页面跳转逻辑实现 如果需要处理登录成功后的页面跳转功能,则可以参考下面的方法来设计目标页面结构以及交互行为: ```typescript @Entry @Component struct Page10 { @State message: string = '跳转成功' build() { Row({ space: 8 }) { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) }.width('100%') }.height('100%') } } ``` 这段代码描述的是一个新的页面组件 (`Page10`) ,当用户完成某些特定动作比如登录之后会被导航至此处显示提示信息“跳转成功”[^3]。 #### 5. 结合实际场景调用 Web Service 接口 对于更复杂的业务流程而言,可能还需要集成第三方提供的 web service api 来增强应用程序的功能性。例如高德地图提供了详细的天气查询接口文档可以帮助开发者快速构建具备实时气象资讯展示能力的小程序应用[^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员的世界你不懂

你的鼓励将是我创造的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值