文章目录
- Axios
- Axios特性
- 安装
- 使用方法
- Axios 实例
- 拦截器
- 取消请求
- 响应结构
- 错误处理
- 在Vue中封装Axios
Axios
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
文档:https://axios.nodejs.cn/
Axios特性
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防止 CSRF
安装
使用 npm:
$ npm install axios
使用 yarn:
$ yarn add axios
使用方法
发送一个 GET 请求:
javascript">axios.get('/user', {params: {ID: 12345}}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);}).finally(function () {// always executed});
Axios 也支持 POST 请求:
javascript">axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});
发送表单数据:
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'}}
)
Axios 实例
我们可以使用自定义配置创建一个新的 axios 实例。
const instance = axios.create({baseURL: 'https://some-domain.com/api/',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});
拦截器
可以在请求或响应被 then 或 catch 处理前拦截它们:
javascript">// Add a request interceptor
axios.interceptors.request.use(function (config) {// Do something before request is sentreturn config;}, function (error) {// Do something with request errorreturn 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 datareturn response;}, function (error) {// Any status codes that falls outside the range of 2xx cause this function to trigger// Do something with response errorreturn Promise.reject(error);});
取消请求
Axios 允许创建自定义的实例,配置默认的请求行为:
javascript
// Create an instance with the default settings
const instance = axios.create({baseURL: 'https://api.example.com'
});// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;// Send a GET request
instance.get('/user/12345').then(function(response){console.log(response.data);});
响应结构
响应的数据结构包括以下几个重要部分:
javascript">axios.get('/user/12345').then(function(response) {console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});
错误处理
处理请求错误时,Axios 会将错误封装在一个统一的对象中:
javascript">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 2xxconsole.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 receivedconsole.log(error.request);} else {// Something happened in setting up the request that triggered an Errorconsole.log('Error', error.message);}console.log(error.config);});
在Vue中封装Axios
import axios from "axios";
import { ElMessage } from "element-plus";const baseURL = "http://127.0.0.1:8000";
const instance = axios.create({baseURL: baseURL,timeout: 5000,
});instance.interceptors.request.use((config) => {// 添加用户tokenreturn config;},(e) => Promise.reject(e)
);// 添加响应拦截器
instance.interceptors.response.use(function (response) {// 2xx 范围内的状态码都会触发该函数。// 对响应数据做点什么return response;},async function async(error) {// 超出 2xx 范围的状态码都会触发该函数。// 对响应错误做点什么if (error.response.status === 401) {// 可验证用户是否登录ElMessage.error("登录状态失效,请重新登录");}ElMessage.error(error.response.data.detail || error.response.data.error || "服务异常");return Promise.reject(error);}
);export default instance;
export { baseURL };