返回
如何利用 Axios 轻松封装各种 HTTP 请求?
前端
2023-12-21 00:00:21
Axios 简介
Axios 是一个非常流行的 JavaScript 库,它可以帮助我们轻松地发送 HTTP 请求。Axios 的优点有很多,比如:
- 语法简单,易于使用
- 支持多种 HTTP 方法
- 支持多种数据格式,如 JSON、XML、文本等
- 支持超时设置
- 支持跨域请求
- 支持文件上传和下载
Axios 封装
封装是指将代码块组织成一个独立的单元,以便在其他地方可以轻松地调用。封装可以提高代码的可重用性和可维护性。
下面,我们将介绍如何利用 Axios 封装各种 HTTP 请求。
GET 请求
import axios from 'axios';
const get = (url, params) => {
return axios.get(url, {
params: params
});
};
POST 请求
import axios from 'axios';
const post = (url, data) => {
return axios.post(url, data);
};
文件上传
import axios from 'axios';
const upload = (url, file) => {
const formData = new FormData();
formData.append('file', file);
return axios.post(url, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
};
文件下载
import axios from 'axios';
const download = (url) => {
return axios.get(url, {
responseType: 'blob'
});
};
使用封装后的函数
封装好 HTTP 请求函数后,我们就可以在其他地方直接调用这些函数来发送请求了。例如:
import { get, post, upload, download } from './api';
// 发送 GET 请求
get('/api/users', {
page: 1,
size: 10
}).then(response => {
console.log(response.data);
});
// 发送 POST 请求
post('/api/users', {
name: 'John Doe',
email: 'johndoe@example.com'
}).then(response => {
console.log(response.data);
});
// 上传文件
upload('/api/files', file).then(response => {
console.log(response.data);
});
// 下载文件
download('/api/files/123').then(response => {
const url = URL.createObjectURL(response.data);
const a = document.createElement('a');
a.href = url;
a.download = 'file.txt';
a.click();
});
跨域请求
在前端发起跨域请求时,我们需要在请求头中加上 withCredentials
属性。这个属性表示请求需要携带 cookie。这样,后端才能知道请求是从哪个域名发起的,并据此决定是否允许请求。
import axios from 'axios';
const get = (url, params) => {
return axios.get(url, {
params: params,
withCredentials: true
});
};
总结
本文介绍了如何利用 Axios 封装各种 HTTP 请求,以及如何在前端发起跨域请求时使用 withCredentials
属性。封装后,我们可以大大提高开发效率,并降低代码重复率。希望本文对您有所帮助。